@mupt-ai/dari-gateway 1.0.324 → 1.0.326

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 (88) hide show
  1. package/README.md +4 -3
  2. package/dist/activity/conversation_detail.d.ts +2 -0
  3. package/dist/activity/conversation_detail.js +259 -0
  4. package/dist/activity/conversation_records.d.ts +129 -0
  5. package/dist/activity/conversation_records.js +318 -0
  6. package/dist/activity/conversations.d.ts +11 -0
  7. package/dist/activity/conversations.js +198 -0
  8. package/dist/activity/core.d.ts +13 -0
  9. package/dist/activity/core.js +613 -0
  10. package/dist/activity/filters.d.ts +71 -0
  11. package/dist/activity/filters.js +169 -0
  12. package/dist/activity/http.d.ts +37 -0
  13. package/dist/activity/http.js +109 -0
  14. package/dist/activity/params.d.ts +40 -0
  15. package/dist/activity/params.js +130 -0
  16. package/dist/activity/people.d.ts +3 -0
  17. package/dist/activity/people.js +413 -0
  18. package/dist/activity/routes.d.ts +2 -0
  19. package/dist/activity/routes.js +23 -0
  20. package/dist/activity/savings.d.ts +12 -0
  21. package/dist/activity/savings.js +102 -0
  22. package/dist/activity/shared.d.ts +15 -0
  23. package/dist/activity/shared.js +26 -0
  24. package/dist/activity/sql.d.ts +52 -0
  25. package/dist/activity/sql.js +124 -0
  26. package/dist/activity/tool_exchanges.d.ts +21 -0
  27. package/dist/activity/tool_exchanges.js +309 -0
  28. package/dist/activity/tool_skill_activity.d.ts +128 -0
  29. package/dist/activity/tool_skill_activity.js +280 -0
  30. package/dist/activity/tool_skill_identities.d.ts +25 -0
  31. package/dist/activity/tool_skill_identities.js +162 -0
  32. package/dist/activity/tools.d.ts +4 -0
  33. package/dist/activity/tools.js +68 -0
  34. package/dist/activity/values.d.ts +45 -0
  35. package/dist/activity/values.js +178 -0
  36. package/dist/context/interaction_fingerprint.js +11 -3
  37. package/dist/context/interaction_fingerprint_format.d.ts +2 -1
  38. package/dist/context/interaction_fingerprint_format.js +2 -0
  39. package/dist/http/handler.d.ts +2 -1
  40. package/dist/http/handler.js +6 -1
  41. package/dist/interaction/types.d.ts +17 -2
  42. package/dist/interaction/types.js +11 -0
  43. package/dist/link/endpoints.js +44 -53
  44. package/dist/platform/platform.d.ts +12 -0
  45. package/dist/protocol/input/anthropic_messages.js +63 -48
  46. package/dist/providers/pi.js +22 -3
  47. package/dist/providers/pi_context.js +15 -5
  48. package/dist/runtime/claude_code/auxiliary_routing.js +34 -3
  49. package/dist/runtime/prepare_routed_completion.d.ts +2 -0
  50. package/dist/runtime/prepare_routed_completion.js +42 -1
  51. package/dist/self_host/activity_store.d.ts +35 -0
  52. package/dist/self_host/activity_store.js +373 -0
  53. package/dist/self_host/main.d.ts +3 -2
  54. package/dist/self_host/main.js +8 -3
  55. package/dist/self_host/platform.d.ts +4 -2
  56. package/dist/self_host/platform.js +35 -3
  57. package/package.json +2 -2
  58. package/src/activity/conversation_detail.ts +283 -0
  59. package/src/activity/conversation_records.ts +403 -0
  60. package/src/activity/conversations.ts +218 -0
  61. package/src/activity/core.ts +678 -0
  62. package/src/activity/filters.ts +206 -0
  63. package/src/activity/http.ts +140 -0
  64. package/src/activity/params.ts +138 -0
  65. package/src/activity/people.ts +471 -0
  66. package/src/activity/routes.ts +26 -0
  67. package/src/activity/savings.ts +121 -0
  68. package/src/activity/shared.ts +36 -0
  69. package/src/activity/sql.ts +139 -0
  70. package/src/activity/tool_exchanges.ts +340 -0
  71. package/src/activity/tool_skill_activity.ts +314 -0
  72. package/src/activity/tool_skill_identities.ts +196 -0
  73. package/src/activity/tools.ts +76 -0
  74. package/src/activity/values.ts +197 -0
  75. package/src/context/interaction_fingerprint.ts +9 -3
  76. package/src/context/interaction_fingerprint_format.ts +6 -1
  77. package/src/http/handler.ts +5 -1
  78. package/src/interaction/types.ts +21 -11
  79. package/src/link/endpoints.ts +44 -54
  80. package/src/platform/platform.ts +12 -0
  81. package/src/protocol/input/anthropic_messages.ts +66 -53
  82. package/src/providers/pi.ts +22 -3
  83. package/src/providers/pi_context.ts +14 -7
  84. package/src/runtime/claude_code/auxiliary_routing.ts +33 -2
  85. package/src/runtime/prepare_routed_completion.ts +60 -2
  86. package/src/self_host/activity_store.ts +423 -0
  87. package/src/self_host/main.ts +17 -3
  88. package/src/self_host/platform.ts +38 -3
@@ -0,0 +1,178 @@
1
+ /* Values as Activity reads and writes them: instants with microseconds,
2
+ exact decimals, and the column values each database returns. Responses
3
+ format them the way Dari's API always has (Python's datetime and Decimal),
4
+ so the dashboard and CLI read the same text from any gateway. */
5
+ const MICROS_PER_MS = 1000;
6
+ const MICROS_PER_SECOND = 1_000_000;
7
+ export function instantFromDate(date) {
8
+ return date.getTime() * MICROS_PER_MS;
9
+ }
10
+ /**
11
+ * Canonical text for an instant: `YYYY-MM-DDTHH:MM:SS.ffffffZ`. Instants are
12
+ * bound and stored in this form, so stored text sorts in time order.
13
+ */
14
+ export function canonicalInstant(instant) {
15
+ const micros = ((instant % MICROS_PER_SECOND) + MICROS_PER_SECOND) % MICROS_PER_SECOND;
16
+ const seconds = (instant - micros) / MICROS_PER_SECOND;
17
+ const base = new Date(seconds * 1000).toISOString().slice(0, 19);
18
+ return `${base}.${String(micros).padStart(6, "0")}Z`;
19
+ }
20
+ /** An instant as Dari's API writes one: fractional seconds only when nonzero. */
21
+ export function formatInstant(instant) {
22
+ const text = canonicalInstant(instant);
23
+ return text.endsWith(".000000Z") ? `${text.slice(0, 19)}Z` : text;
24
+ }
25
+ /** A timestamp column as either database returns it. */
26
+ export function readInstant(value) {
27
+ if (value instanceof Date)
28
+ return instantFromDate(value);
29
+ if (typeof value === "string") {
30
+ const parsed = parseInstantText(value);
31
+ if (parsed !== null && !parsed.naive)
32
+ return parsed.instant;
33
+ }
34
+ throw new Error(`Unreadable timestamp ${JSON.stringify(value)}.`);
35
+ }
36
+ export function readOptionalInstant(value) {
37
+ return value === null || value === undefined ? null : readInstant(value);
38
+ }
39
+ const DATE_TIME = /^(\d{4})-(\d{2})-(\d{2})(?:[T ](\d{2}):(\d{2})(?::(\d{2})(?:[.,](\d{1,6}))?)?)?(Z|z|[+-]\d{2}(?::?\d{2})?)?$/;
40
+ /**
41
+ * Parse a datetime as Dari's API accepts one in a query: ISO 8601 (a date
42
+ * alone is midnight), or Unix seconds (milliseconds above 2e10). `naive` is a
43
+ * value without a UTC offset; its instant reads it as UTC. Null when it is
44
+ * not a datetime.
45
+ */
46
+ export function parseInstantText(text) {
47
+ const trimmed = text.trim();
48
+ if (/^[+-]?\d+(\.\d+)?$/.test(trimmed)) {
49
+ let seconds = Number(trimmed);
50
+ if (!Number.isFinite(seconds))
51
+ return null;
52
+ if (Math.abs(seconds) > 2e10)
53
+ seconds /= 1000;
54
+ return { instant: Math.round(seconds * MICROS_PER_SECOND), naive: false };
55
+ }
56
+ const match = DATE_TIME.exec(trimmed);
57
+ if (match === null)
58
+ return null;
59
+ const [, year, month, day, hour = "0", minute = "0", second = "0", fraction = "", zone] = match;
60
+ const hasTime = match[4] !== undefined;
61
+ const fields = [Number(year), Number(month), Number(day), Number(hour), Number(minute), Number(second)];
62
+ const [y, mo, d, h, mi, s] = fields;
63
+ if (mo < 1 || mo > 12 || d < 1 || h > 23 || mi > 59 || s > 59)
64
+ return null;
65
+ const ms = Date.UTC(y, mo - 1, d, h, mi, s);
66
+ const check = new Date(ms);
67
+ if (check.getUTCDate() !== d || check.getUTCMonth() !== mo - 1)
68
+ return null;
69
+ let instant = ms * MICROS_PER_MS + Number(fraction.padEnd(6, "0") || "0");
70
+ if (zone === undefined || !hasTime) {
71
+ return zone === undefined ? { instant, naive: true } : null;
72
+ }
73
+ if (zone !== "Z" && zone !== "z") {
74
+ const sign = zone.startsWith("-") ? -1 : 1;
75
+ const digits = zone.slice(1).replace(":", "");
76
+ const offsetMinutes = Number(digits.slice(0, 2)) * 60 + Number(digits.slice(2) || "0");
77
+ if (offsetMinutes >= 24 * 60)
78
+ return null;
79
+ instant -= sign * offsetMinutes * 60 * MICROS_PER_SECOND;
80
+ }
81
+ return { instant, naive: false };
82
+ }
83
+ const DECIMAL = /^([+-])?(\d*)(?:\.(\d*))?(?:[eE]([+-]?\d+))?$/;
84
+ export function parseDecimal(value) {
85
+ const text = typeof value === "number" ? String(value) : value.trim();
86
+ const match = DECIMAL.exec(text);
87
+ if (match === null || (match[2] === "" && (match[3] ?? "") === "")) {
88
+ throw new Error(`Not a decimal: ${JSON.stringify(value)}.`);
89
+ }
90
+ const [, sign, whole = "", fraction = "", exponent = "0"] = match;
91
+ const digits = `${whole}${fraction}` || "0";
92
+ const coefficient = BigInt(digits) * (sign === "-" ? -1n : 1n);
93
+ return { coefficient, exponent: Number(exponent) - fraction.length };
94
+ }
95
+ export function addDecimals(left, right) {
96
+ const exponent = Math.min(left.exponent, right.exponent);
97
+ return {
98
+ coefficient: left.coefficient * 10n ** BigInt(left.exponent - exponent)
99
+ + right.coefficient * 10n ** BigInt(right.exponent - exponent),
100
+ exponent,
101
+ };
102
+ }
103
+ export function subtractDecimals(left, right) {
104
+ return addDecimals(left, { coefficient: -right.coefficient, exponent: right.exponent });
105
+ }
106
+ export function compareDecimals(left, right) {
107
+ const difference = subtractDecimals(left, right).coefficient;
108
+ return difference === 0n ? 0 : difference < 0n ? -1 : 1;
109
+ }
110
+ /** Python's `str(Decimal)`. */
111
+ export function formatDecimal(value) {
112
+ const negative = value.coefficient < 0n;
113
+ const coefficient = (negative ? -value.coefficient : value.coefficient).toString();
114
+ const leftDigits = value.exponent + coefficient.length;
115
+ const dotPlace = value.exponent <= 0 && leftDigits > -6 ? leftDigits : 1;
116
+ let integer;
117
+ let fraction;
118
+ if (dotPlace <= 0) {
119
+ integer = "0";
120
+ fraction = `.${"0".repeat(-dotPlace)}${coefficient}`;
121
+ }
122
+ else if (dotPlace >= coefficient.length) {
123
+ integer = coefficient + "0".repeat(dotPlace - coefficient.length);
124
+ fraction = "";
125
+ }
126
+ else {
127
+ integer = coefficient.slice(0, dotPlace);
128
+ fraction = `.${coefficient.slice(dotPlace)}`;
129
+ }
130
+ const exponent = leftDigits === dotPlace
131
+ ? ""
132
+ : `E${leftDigits - dotPlace >= 0 ? "+" : ""}${leftDigits - dotPlace}`;
133
+ return `${negative ? "-" : ""}${integer}${fraction}${exponent}`;
134
+ }
135
+ /** Python's `decimal_text`: a numeric column's value as API text, or null. */
136
+ export function decimalText(value) {
137
+ if (value === null || value === undefined)
138
+ return null;
139
+ return formatDecimal(parseDecimal(value));
140
+ }
141
+ /** Add the present values to zero; null when none is present. */
142
+ export function sumDecimalText(values) {
143
+ let total = null;
144
+ for (const value of values) {
145
+ if (value === null || value === undefined)
146
+ continue;
147
+ const parsed = parseDecimal(value);
148
+ total = total === null ? addDecimals({ coefficient: 0n, exponent: 0 }, parsed) : addDecimals(total, parsed);
149
+ }
150
+ return total === null ? null : formatDecimal(total);
151
+ }
152
+ /* Column values as the two databases return them: Postgres counts and
153
+ bigints arrive as text, SQLite booleans as 0 and 1, SQLite JSON as text. */
154
+ export function readInt(value) {
155
+ if (value === null || value === undefined)
156
+ return 0;
157
+ return typeof value === "number" ? value : Number(value);
158
+ }
159
+ export function readOptionalInt(value) {
160
+ return value === null || value === undefined ? null : readInt(value);
161
+ }
162
+ export function readOptionalBool(value) {
163
+ if (value === null || value === undefined)
164
+ return null;
165
+ return value === true || value === 1 || value === "1" || value === "t" || value === "true";
166
+ }
167
+ export function readBool(value) {
168
+ return readOptionalBool(value) ?? false;
169
+ }
170
+ /** A JSON column: Postgres returns it parsed, SQLite as its text. */
171
+ export function readJson(db, value) {
172
+ if (value === null || value === undefined)
173
+ return null;
174
+ return db.dialect === "sqlite" && typeof value === "string" ? JSON.parse(value) : value;
175
+ }
176
+ export function readOptionalString(value) {
177
+ return value === null || value === undefined ? null : String(value);
178
+ }
@@ -224,6 +224,7 @@ function fingerprintChatInputSteps(items, target, toolCallApi, policy) {
224
224
  ...(item.role === "assistant" && pendingReasoning.length > 0
225
225
  ? { reasoning: pendingReasoning }
226
226
  : {}),
227
+ ...(item.toolsAdded?.length ? { toolsAdded: item.toolsAdded } : {}),
227
228
  });
228
229
  pendingReasoning = [];
229
230
  pendingReasoningItemIndex = -1;
@@ -355,6 +356,7 @@ function fingerprintSteps(items, target, toolCallApi, policy) {
355
356
  resultCallId: null,
356
357
  ...(policy.includeItemIds && item.id ? { itemId: item.id } : {}),
357
358
  ...(policy.includePhase && item.phase ? { phase: item.phase } : {}),
359
+ ...(item.toolsAdded?.length ? { toolsAdded: item.toolsAdded } : {}),
358
360
  });
359
361
  }
360
362
  return steps;
@@ -443,20 +445,26 @@ function conversationFingerprintSteps(steps) {
443
445
  if (!sawConversationStep)
444
446
  continue;
445
447
  const text = fingerprintReadableText(step.content);
446
- if (!text)
448
+ // Tools a system message adds stay where they were added, as Pi sends them.
449
+ const added = step.toolsAdded ?? [];
450
+ if (!text && added.length === 0)
447
451
  continue;
448
452
  const previous = positional.at(-1);
449
453
  if (previous?.actor === "user" || previous?.actor === "tool") {
450
- previous.content = appendPositionalFingerprintText(previous.content, text);
454
+ if (text)
455
+ previous.content = appendPositionalFingerprintText(previous.content, text);
456
+ if (added.length > 0)
457
+ previous.toolsAdded = [...(previous.toolsAdded ?? []), ...added];
451
458
  previous.itemIndex = step.itemIndex;
452
459
  continue;
453
460
  }
454
461
  positional.push({
455
462
  actor: "user",
456
- content: [{ type: "text", text }],
463
+ content: text ? [{ type: "text", text }] : [],
457
464
  calls: [],
458
465
  resultCallId: null,
459
466
  itemIndex: step.itemIndex,
467
+ ...(added.length > 0 ? { toolsAdded: added } : {}),
460
468
  });
461
469
  }
462
470
  return positional;
@@ -1,4 +1,4 @@
1
- import type { InteractionContent, InteractionRequest } from "../interaction/types.js";
1
+ import type { InteractionContent, InteractionRequest, InteractionTool } from "../interaction/types.js";
2
2
  export type FingerprintContent = string | Array<{
3
3
  type: "text";
4
4
  text: string;
@@ -34,6 +34,7 @@ export type InteractionFingerprintStep = {
34
34
  itemId?: string;
35
35
  phase?: "commentary" | "final_answer";
36
36
  reasoning?: ReasoningFingerprint[];
37
+ toolsAdded?: InteractionTool[];
37
38
  };
38
39
  export declare function interactionFingerprintHeadHash(routerId: string, request: InteractionRequest): string;
39
40
  export declare function interactionOptionsFingerprints(request: InteractionRequest): {
@@ -14,6 +14,7 @@ export function interactionFingerprintHeadHash(routerId, request) {
14
14
  systemItems.push({
15
15
  actor: item.role,
16
16
  content: systemFingerprintContent(item.content, item.contentShape),
17
+ ...(item.toolsAdded?.length ? { toolsAdded: item.toolsAdded } : {}),
17
18
  });
18
19
  }
19
20
  return sha256(stableStringify({
@@ -55,6 +56,7 @@ export function canonicalInteractionFingerprintStep(step) {
55
56
  ...(step.itemId ? { itemId: step.itemId } : {}),
56
57
  ...(step.phase ? { phase: step.phase } : {}),
57
58
  ...(step.reasoning ? { reasoning: step.reasoning } : {}),
59
+ ...(step.toolsAdded?.length ? { toolsAdded: step.toolsAdded } : {}),
58
60
  });
59
61
  }
60
62
  export function interactionFingerprintContent(content, shape) {
@@ -7,7 +7,8 @@ export type GatewayHandlerOptions = {
7
7
  /**
8
8
  * The gateway's routed HTTP surface: `/v1/{chat/completions,responses,
9
9
  * messages,models}` on the default router and `/{router_id}/v1/...` on a
10
- * named one, and the Dari Link grant endpoints under `/v1/link/`. Binds
10
+ * named one, the Dari Link grant endpoints under `/v1/link/`, and the
11
+ * Activity reads under `/v1/organizations/{organization}/routing/activity/`. Binds
11
12
  * `options.platform` for every request it serves.
12
13
  */
13
14
  export declare function createRequestHandler(options: GatewayHandlerOptions): (request: Request) => Promise<Response>;
@@ -1,4 +1,5 @@
1
1
  import { handleResponses, handleResponsesWebSocketFallback, } from "../ingress/codex.js";
2
+ import { handleActivityRequest } from "../activity/http.js";
2
3
  import { handleLinkRequest, LINK_METADATA_PATH, LINK_ROUTE_PREFIX } from "../link/endpoints.js";
3
4
  import { handleModels } from "../ingress/models.js";
4
5
  import { handleMuseCodeModels } from "../ingress/muse_models.js";
@@ -10,7 +11,8 @@ import { errorResponse, HttpError } from "./errors.js";
10
11
  /**
11
12
  * The gateway's routed HTTP surface: `/v1/{chat/completions,responses,
12
13
  * messages,models}` on the default router and `/{router_id}/v1/...` on a
13
- * named one, and the Dari Link grant endpoints under `/v1/link/`. Binds
14
+ * named one, the Dari Link grant endpoints under `/v1/link/`, and the
15
+ * Activity reads under `/v1/organizations/{organization}/routing/activity/`. Binds
14
16
  * `options.platform` for every request it serves.
15
17
  */
16
18
  export function createRequestHandler(options) {
@@ -36,6 +38,9 @@ export function createRequestHandler(options) {
36
38
  if (url.pathname.startsWith(LINK_ROUTE_PREFIX) || url.pathname === LINK_METADATA_PATH) {
37
39
  return await handleLinkRequest(request, options.platform);
38
40
  }
41
+ const activity = await handleActivityRequest(request, options.platform.activity);
42
+ if (activity !== null)
43
+ return activity;
39
44
  const endpoint = routedEndpoint(url.pathname);
40
45
  if (endpoint?.protocol === "chat" && request.method === "POST") {
41
46
  return await handleChatCompletions(request, endpoint.routerId, selectorBackend);
@@ -52,6 +52,7 @@ export type InteractionMessage = {
52
52
  contentShape: "string" | "parts" | "null" | "absent";
53
53
  phase?: "commentary" | "final_answer";
54
54
  source?: ProviderIdentity;
55
+ toolsAdded?: InteractionTool[];
55
56
  };
56
57
  export type InteractionReasoning = {
57
58
  type: "reasoning";
@@ -107,12 +108,26 @@ export type InteractionCompaction = {
107
108
  };
108
109
  export type InteractionItem = InteractionCompaction | InteractionMessage | InteractionReasoning | InteractionToolCall | InteractionToolResult | InteractionReasoningConfiguration | InteractionHostedToolCall;
109
110
  export type InteractionOutputItem = InteractionCompaction | InteractionMessage | InteractionReasoning | InteractionToolCall | InteractionHostedToolCall;
110
- export type ServerToolKind = "bash_20250124" | "text_editor_20250124" | "tool_search_tool_20250919" | "tool_search_tool_regex_20250919" | "tool_search_tool_regex" | "tool_search_tool_regex_20251119" | "tool_search_tool_bm25" | "tool_search_tool_bm25_20251119" | AnthropicWebSearchToolType;
111
+ export declare const ANTHROPIC_TOOL_TYPE_KINDS: {
112
+ readonly bash_20250124: "client_tool";
113
+ readonly text_editor_20250124: "client_tool";
114
+ readonly tool_search_tool_20250919: "server_tool";
115
+ readonly tool_search_tool_regex_20250919: "server_tool";
116
+ readonly tool_search_tool_regex: "server_tool";
117
+ readonly tool_search_tool_regex_20251119: "server_tool";
118
+ readonly tool_search_tool_bm25: "server_tool";
119
+ readonly tool_search_tool_bm25_20251119: "server_tool";
120
+ };
121
+ type AnthropicToolTypeKinds = typeof ANTHROPIC_TOOL_TYPE_KINDS;
122
+ export type ClientToolType = {
123
+ [K in keyof AnthropicToolTypeKinds]: AnthropicToolTypeKinds[K] extends "client_tool" ? K : never;
124
+ }[keyof AnthropicToolTypeKinds];
125
+ export type ServerToolKind = keyof AnthropicToolTypeKinds | AnthropicWebSearchToolType;
111
126
  export type AnthropicWebSearchToolType = `web_search_${number}`;
112
127
  export type ClientTool = {
113
128
  kind: "client_tool";
114
129
  name: string;
115
- type: "bash_20250124" | "text_editor_20250124";
130
+ type: ClientToolType;
116
131
  description?: string;
117
132
  };
118
133
  export type FunctionTool = {
@@ -3,3 +3,14 @@ export function isBackgroundRequest(request) {
3
3
  || request.agentContext?.requestClass === "compaction"
4
4
  || request.agentContext?.requestClass === "side_reply";
5
5
  }
6
+ // Anthropic tool types the gateway accepts, each with the side that runs it.
7
+ export const ANTHROPIC_TOOL_TYPE_KINDS = {
8
+ bash_20250124: "client_tool",
9
+ text_editor_20250124: "client_tool",
10
+ tool_search_tool_20250919: "server_tool",
11
+ tool_search_tool_regex_20250919: "server_tool",
12
+ tool_search_tool_regex: "server_tool",
13
+ tool_search_tool_regex_20251119: "server_tool",
14
+ tool_search_tool_bm25: "server_tool",
15
+ tool_search_tool_bm25_20251119: "server_tool",
16
+ };
@@ -968,7 +968,7 @@ async function authorizeSubmit(link, request, form) {
968
968
  if (decision === "deny")
969
969
  return redirect(back, { error: "access_denied" }, [endConnect]);
970
970
  if (decision === "sign_out")
971
- return seeAuthorize(authorize, signOutCookies(request));
971
+ return signOut(request, approval, `${AUTHORIZE_PATH}?${authorizeQuery(authorize)}`);
972
972
  if (decision === "select")
973
973
  return selectPage(approval, authorize, undefined, [endConnect]);
974
974
  if (decision === "connect") {
@@ -1012,16 +1012,6 @@ async function authorizeSubmit(link, request, form) {
1012
1012
  if (decision === "complete" && connect !== null) {
1013
1013
  return await finishConnect(approval, request, authorize, session, connect, form.get("authorization_response")?.trim() ?? "");
1014
1014
  }
1015
- // Removing a plan or key asks once, then deletes what Dari stored for it.
1016
- const removing = form.get("remove") ?? form.get("remove_id");
1017
- if (removing !== null && session !== null) {
1018
- const subscription = (await approval.subscriptions(session.subject)).find((candidate) => candidate.id === removing);
1019
- if (subscription !== undefined && decision !== "remove")
1020
- return removePage(authorize, session, subscription);
1021
- if (subscription !== undefined && sameText(form.get("csrf") ?? "", session.csrf))
1022
- await approval.remove(session.subject, removing);
1023
- return seeAuthorize(authorize, [endConnect]);
1024
- }
1025
1015
  // Anything else goes back to where the user stands.
1026
1016
  if (decision !== "approve" || session === null)
1027
1017
  return seeAuthorize(authorize, [endConnect]);
@@ -1141,12 +1131,8 @@ async function connectionsSubmit(approval, request, form) {
1141
1131
  if (session === null || !sameText(form.get("csrf") ?? "", session.csrf))
1142
1132
  return back;
1143
1133
  const decision = form.get("decision");
1144
- if (decision === "sign_out") {
1145
- const headers = new Headers({ Location: CONNECTIONS_PATH, "Cache-Control": "no-store" });
1146
- for (const cookie of signOutCookies(request))
1147
- headers.append("Set-Cookie", cookie);
1148
- return new Response(null, { status: 303, headers });
1149
- }
1134
+ if (decision === "sign_out")
1135
+ return signOut(request, approval, CONNECTIONS_PATH);
1150
1136
  const grantId = form.get("grant_id") ?? "";
1151
1137
  if (decision === "disconnect") {
1152
1138
  await approval.disconnect(session.subject, grantId);
@@ -1312,9 +1298,20 @@ function userCookie(request, approval, subject) {
1312
1298
  ? signedCookie(request, approval.sessionSecret(), USER_COOKIE, { sub: subject }, USER_SECONDS)
1313
1299
  : signedCookie(request, approval.sessionSecret(), USER_COOKIE, { sub: subject, account: true }, ACCOUNT_SECONDS);
1314
1300
  }
1315
- // Signing out leaves nothing of the user's: not who they are, nor a provider sign-in under way.
1316
- function signOutCookies(request) {
1317
- return [clearCookie(request, USER_COOKIE), clearCookie(request, CONNECT_COOKIE)];
1301
+ // Signing out leaves nothing of the user's: not who they are, nor a provider
1302
+ // sign-in under way. A platform with accounts ends its own sign-in too, then
1303
+ // returns the user to `next`, so the next sign-in can be another account.
1304
+ function signOut(request, approval, next) {
1305
+ let location = next;
1306
+ if (approval.signIn !== undefined) {
1307
+ const url = new URL(approval.signIn.signOutUrl());
1308
+ url.searchParams.set("next", next);
1309
+ location = url.toString();
1310
+ }
1311
+ const headers = new Headers({ Location: location, "Cache-Control": "no-store" });
1312
+ headers.append("Set-Cookie", clearCookie(request, USER_COOKIE));
1313
+ headers.append("Set-Cookie", clearCookie(request, CONNECT_COOKIE));
1314
+ return new Response(null, { status: 303, headers });
1318
1315
  }
1319
1316
  function clearCookie(request, cookie) {
1320
1317
  return `${cookie}=; Path=${COOKIE_PATH}; Max-Age=0; HttpOnly; SameSite=Lax${isHttps(request) ? "; Secure" : ""}`;
@@ -1478,48 +1475,38 @@ function choosePage(authorize, session, subscriptions, current, error) {
1478
1475
  body: `<h1>${current === null ? `Share With ${app}` : `Update Plans For ${app}`}</h1>
1479
1476
  <input type="hidden" name="csrf" value="${session.csrf}">
1480
1477
  ${plans.map((plan) => planOption(authorize, plan, ticked.has(plan.id))).join("\n")}
1481
- <button class="btn ghost" type="submit" name="decision" value="select" formnovalidate>${ICONS.plus}Connect Another</button>
1482
- ${session.account ? SIGN_OUT : ""}`,
1478
+ <div class="actions"><button class="btn ghost" type="submit" name="decision" value="select" formnovalidate>${ICONS.plus}Connect Another</button><span><a class="btn ghost" href="${CONNECTIONS_PATH}" target="_blank" rel="noopener">Manage</a>${session.account ? SIGN_OUT : ""}</span></div>`,
1483
1479
  footer: `<button class="btn primary" type="submit" name="decision" value="approve">${current === null ? "Allow" : "Save"}</button>
1484
1480
  <p class="fine">${app} keeps access until you or it disconnect. Its requests fail while a plan is at its usage limit.</p>`,
1485
1481
  });
1486
1482
  }
1487
- // What the user is about to delete, and the one button that deletes it.
1488
- function removePage(authorize, session, subscription) {
1489
- const key = subscription.apiKeyProvider;
1490
- const name = key === undefined ? KINDS[subscription.provider]?.name ?? subscription.name : subscription.name;
1491
- return pane(authorize, {
1492
- title: `Remove ${name}`,
1493
- step: "choose_plans",
1494
- back: "home",
1495
- body: `<span class="who">${logo(key ?? subscription.provider, name)}</span>
1496
- <h1>Remove ${escapeHtml(name)}${key === undefined ? "" : " API Key"}</h1>
1497
- <p>${escapeHtml(planLabel(subscription))}</p>
1498
- <p>Dari deletes ${key === undefined ? "the sign-in it holds for this plan" : "this key"}. Every app you shared it with stops using it.</p>
1499
- <input type="hidden" name="csrf" value="${session.csrf}">
1500
- <input type="hidden" name="remove_id" value="${escapeHtml(subscription.id)}">`,
1501
- footer: `<button class="btn danger" type="submit" name="decision" value="remove">Remove</button>`,
1502
- });
1503
- }
1504
1483
  function planOption(authorize, subscription, ticked) {
1505
- const box = `<input type="checkbox" name="credential_id" value="${escapeHtml(subscription.id)}"${ticked ? " checked" : ""}><button class="nav drop" type="submit" name="remove" value="${escapeHtml(subscription.id)}" formnovalidate aria-label="Remove">${ICONS.trash}</button>`;
1484
+ const box = `<input type="checkbox" name="credential_id" value="${escapeHtml(subscription.id)}"${ticked ? " checked" : ""}>`;
1506
1485
  if (subscription.apiKeyProvider !== undefined) {
1507
1486
  return `<label class="option pick">${logo(subscription.apiKeyProvider, subscription.name)}<span class="grow"><strong>${escapeHtml(subscription.name)}</strong><small>API key &middot; ${escapeHtml(planLabel(subscription))}</small></span>${box}</label>`;
1508
1487
  }
1509
1488
  const kind = subscription.provider;
1510
1489
  const only = subscriptionClient(kind);
1490
+ // What the app says it does with the plan, on hover.
1511
1491
  const purpose = authorize.purposes[only === "claude_code" || only === "muse_code" ? only : "any_app"];
1512
- const binding = subscription.usage.filter((window) => window.modelFamily === undefined).reduce((most, window) => most === null || window.utilization > most.utilization ? window : most, null);
1513
- const notes = [
1514
- planLabel(subscription),
1515
- ...(subscription.unavailableUntil
1516
- ? [`At its usage limit until ${new Date(subscription.unavailableUntil).toUTCString()}`]
1517
- : binding !== null
1518
- ? [`${Math.round(binding.utilization * 100)}% of its quota used`]
1519
- : []),
1520
- ...(purpose ? [`${authorize.app.name} says: ${purpose.replace(/[.\s]+$/, "")}`] : []),
1521
- ];
1522
- return `<label class="option pick">${logo(kind, KINDS[kind].name)}<span class="grow"><strong>${KINDS[kind].name}</strong><small>${notes.map(escapeHtml).join(" &middot; ")}</small></span>${box}</label>`;
1492
+ return `<label class="option pick"${purpose === undefined ? "" : ` title="${escapeHtml(purpose)}"`}>${logo(kind, KINDS[kind].name)}<span class="grow"><strong>${KINDS[kind].name}</strong>${meter(subscription, planLabel(subscription))}</span>${box}</label>`;
1493
+ }
1494
+ // The plan's account, and how much of its quota it used as the dashboard
1495
+ // shows it: a bar for its fullest shared window that has not reset, red at
1496
+ // the limit.
1497
+ function meter(subscription, account) {
1498
+ const now = Date.now();
1499
+ const held = subscription.unavailableUntil !== null && Date.parse(subscription.unavailableUntil) > now ? subscription.unavailableUntil : null;
1500
+ const fullest = subscription.usage
1501
+ .filter((window) => window.modelFamily === undefined && Date.parse(window.resetsAt) > now)
1502
+ .reduce((most, window) => most === null || window.utilization > most.utilization ? window : most, null);
1503
+ const shown = held !== null
1504
+ ? { percent: 100, until: held }
1505
+ : fullest === null ? null : { percent: Math.min(100, Math.round(fullest.utilization * 100)), until: fullest.resetsAt };
1506
+ if (shown === null)
1507
+ return `<small>${escapeHtml(account)}</small>`;
1508
+ const full = shown.percent >= 100;
1509
+ return `<span class="meter${full ? " full" : ""}" title="${full ? "Until" : "Resets"} ${escapeHtml(new Date(shown.until).toUTCString())}"><small>${escapeHtml(account)}</small><span class="pct">${full ? "Limit Reached" : `${shown.percent}%`}</span><span class="bar" role="meter" aria-label="Quota Used" aria-valuenow="${shown.percent}" aria-valuemin="0" aria-valuemax="100"><span style="width:${Math.max(shown.percent, 1)}%"></span></span></span>`;
1523
1510
  }
1524
1511
  // A provider's mark, or without one the first letter of its name.
1525
1512
  function logo(id, name) {
@@ -1635,9 +1622,9 @@ small{display:block;color:var(--faint);font-size:12px;line-height:1.4;overflow-w
1635
1622
  .option strong{display:block;font-size:14px;line-height:1.35}
1636
1623
  .option.slim{flex-direction:row;align-items:center;gap:10px;padding:10px 12px}.slim .logo{width:16px;height:16px}.slim strong{font-size:13px}
1637
1624
  .option.pick{flex-direction:row;align-items:center;margin:0 0 8px;padding:12px}.grow{flex:1;min-width:0}
1638
- input[type=checkbox]{appearance:none;-webkit-appearance:none;flex:none;display:grid;place-content:center;width:16px;height:16px;margin:0;border:1px solid rgba(237,237,237,.3);border-radius:4px;background:transparent;cursor:pointer}
1625
+ input[type=checkbox]{appearance:none;-webkit-appearance:none;flex:none;display:grid;place-content:center;width:20px;height:20px;margin:0 0 0 4px;border:1.5px solid rgba(237,237,237,.25);border-radius:50%;background:transparent;cursor:pointer;transition:background-color .15s,border-color .15s}
1639
1626
  input[type=checkbox]:checked{border-color:var(--ink);background:var(--ink)}
1640
- input[type=checkbox]:checked::after{content:"";width:8px;height:4px;margin-top:-2px;border:solid var(--page);border-width:0 0 2px 2px;transform:rotate(-45deg)}
1627
+ input[type=checkbox]:checked::after{content:"";width:9px;height:5px;margin-top:-2px;border:solid var(--card);border-width:0 0 2px 2px;transform:rotate(-45deg)}
1641
1628
  .who{display:inline-flex;align-items:center;justify-content:center;width:40px;height:40px;margin:0 0 16px;border:1px solid var(--rule);border-radius:6px;background:var(--page)}
1642
1629
  .step{display:flex;gap:12px;margin:0 0 20px}.step>div{flex:1;min-width:0}.step p,.step label{display:block;color:var(--muted);margin:0 0 10px}
1643
1630
  .n{flex:none;display:inline-flex;align-items:center;justify-content:center;width:20px;height:20px;border-radius:4px;background:rgba(237,237,237,.07);color:var(--muted);font-size:12px}
@@ -1656,6 +1643,10 @@ input[type=text]:focus-visible,input[type=password]:focus-visible{outline:1px so
1656
1643
  .nav.drop{position:static;flex:none;width:28px;height:28px;margin:0 -4px 0 0;color:var(--faint)}
1657
1644
  .btn.outline{border-color:var(--edge)}.btn.outline:hover{border-color:rgba(237,237,237,.4);background:var(--hover)}
1658
1645
  .btn.ghost{height:32px;margin:4px 0 0 -8px;padding:0 10px 0 8px;font-size:13px;color:var(--muted)}.btn.ghost:hover{background:rgba(237,237,237,.06);color:var(--ink)}
1646
+ .meter{display:flex;flex-wrap:wrap;align-items:baseline;gap:0 8px}.meter small{flex:1;min-width:0}
1647
+ .pct{flex:none;color:var(--muted);font-size:12px;font-variant-numeric:tabular-nums}.full .pct{color:#e5484d}
1648
+ .bar{flex:0 0 100%;height:4px;margin:8px 0 2px;border-radius:999px;background:rgba(237,237,237,.08);overflow:hidden}.bar>span{display:block;height:100%;border-radius:999px;background:var(--mint)}.full .bar>span{background:#d64548}
1649
+ .actions{display:flex;justify-content:space-between;margin:4px -8px 0}.actions .btn.ghost{margin:0}.actions span{display:flex}
1659
1650
  .fine{color:var(--faint);font-size:12px;margin:12px 0 0;text-align:center}
1660
1651
  .card{display:block;margin:0 0 12px;padding:14px 12px;border:1px solid var(--rule);border-radius:6px}.card>small{margin:2px 0 0}.card .field{margin:16px 0 8px}
1661
1652
  .row{display:flex;gap:8px;margin:16px 0 0}.row .btn{flex:1}
@@ -1,3 +1,4 @@
1
+ import type { ActivityPlatform } from "../activity/http.js";
1
2
  import type { Provider, ReasoningEffort, RoutingStrategy } from "@mupt-ai/dari-router/policy-engine";
2
3
  import type { HarnessConversationIdentity } from "../runtime/harness_identity/index.js";
3
4
  import type { InteractionRequest, SourceProtocol } from "../interaction/types.js";
@@ -79,6 +80,12 @@ export type GatewayPlatform = {
79
80
  * and nothing else. Without it the `/v1/link/...` endpoints answer 404.
80
81
  */
81
82
  link?: LinkPlatform;
83
+ /**
84
+ * Optional. Activity: the routed requests' usage, spend, conversations, and
85
+ * tools, read under `/v1/organizations/{organization}/routing/activity/`.
86
+ * Without it those endpoints answer 404.
87
+ */
88
+ activity?: ActivityPlatform;
82
89
  };
83
90
  /**
84
91
  * Dari Link as the gateway's endpoints use it. A platform builds it with
@@ -239,10 +246,15 @@ export type LinkApprovalPage = {
239
246
  * The platform's own sign-in. The page sends the user to `url()` with `state`
240
247
  * and `next`; the platform signs them in and returns them to
241
248
  * `/v1/link/session` with the same `next` and a ticket for that state.
249
+ * Signing out sends the user to `signOutUrl()` with `next`; the platform ends
250
+ * its own sign-in and returns them to `next`, so the next sign-in can be
251
+ * another account.
242
252
  */
243
253
  export type LinkSignIn = {
244
254
  /** Throws HttpError(503, `link_not_configured`) when the platform has none. */
245
255
  url(): string;
256
+ /** Throws HttpError(503, `link_not_configured`) when the platform has none. */
257
+ signOutUrl(): string;
246
258
  /** Who a ticket signed in, for which state, and when (epoch ms); null for no ticket. */
247
259
  redeem(ticket: string): Promise<{
248
260
  subject: string;