@mupt-ai/dari-gateway 1.0.334 → 1.0.335

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 (66) hide show
  1. package/dist/activity/conversation_detail.js +4 -1
  2. package/dist/activity/conversations.js +2 -1
  3. package/dist/activity/http.d.ts +28 -3
  4. package/dist/activity/http.js +15 -10
  5. package/dist/activity/imports.d.ts +29 -0
  6. package/dist/activity/imports.js +230 -0
  7. package/dist/activity/pull_requests.d.ts +29 -0
  8. package/dist/activity/pull_requests.js +295 -0
  9. package/dist/activity/routes.d.ts +1 -1
  10. package/dist/activity/routes.js +7 -1
  11. package/dist/http/handler.d.ts +3 -2
  12. package/dist/http/handler.js +8 -2
  13. package/dist/ingress/git_events.d.ts +2 -0
  14. package/dist/ingress/git_events.js +143 -0
  15. package/dist/link/budget.d.ts +27 -2
  16. package/dist/link/budget.js +63 -1
  17. package/dist/link/endpoints.js +179 -36
  18. package/dist/link/errors.d.ts +2 -0
  19. package/dist/link/errors.js +11 -2
  20. package/dist/link/grants.d.ts +6 -5
  21. package/dist/link/grants.js +11 -9
  22. package/dist/link/service.d.ts +27 -6
  23. package/dist/link/service.js +145 -21
  24. package/dist/link/sqlite_store.d.ts +7 -2
  25. package/dist/link/sqlite_store.js +57 -6
  26. package/dist/platform/platform.d.ts +72 -3
  27. package/dist/protocol/input/router_model.d.ts +1 -0
  28. package/dist/protocol/input/router_model.js +6 -2
  29. package/dist/runtime/runtime_reporter.d.ts +1 -0
  30. package/dist/runtime/runtime_reporter.js +3 -0
  31. package/dist/self_host/activity_store.d.ts +15 -2
  32. package/dist/self_host/activity_store.js +60 -7
  33. package/dist/self_host/platform.js +6 -0
  34. package/dist/self_host/resolve.d.ts +4 -5
  35. package/dist/self_host/resolve.js +20 -22
  36. package/dist/telemetry/report.js +21 -2
  37. package/dist/telemetry/tools/git_events.d.ts +36 -0
  38. package/dist/telemetry/tools/git_events.js +109 -0
  39. package/dist/telemetry/tools/observations.d.ts +8 -1
  40. package/dist/telemetry/tools/observations.js +1 -1
  41. package/dist/types.d.ts +1 -0
  42. package/package.json +2 -2
  43. package/src/activity/conversation_detail.ts +4 -1
  44. package/src/activity/conversations.ts +3 -2
  45. package/src/activity/http.ts +43 -12
  46. package/src/activity/imports.ts +278 -0
  47. package/src/activity/pull_requests.ts +342 -0
  48. package/src/activity/routes.ts +8 -2
  49. package/src/http/handler.ts +8 -2
  50. package/src/ingress/git_events.ts +145 -0
  51. package/src/link/budget.ts +80 -4
  52. package/src/link/endpoints.ts +171 -20
  53. package/src/link/errors.ts +12 -2
  54. package/src/link/grants.ts +22 -12
  55. package/src/link/service.ts +187 -24
  56. package/src/link/sqlite_store.ts +73 -10
  57. package/src/platform/platform.ts +57 -4
  58. package/src/protocol/input/router_model.ts +6 -2
  59. package/src/runtime/runtime_reporter.ts +5 -0
  60. package/src/self_host/activity_store.ts +79 -8
  61. package/src/self_host/platform.ts +6 -0
  62. package/src/self_host/resolve.ts +20 -25
  63. package/src/telemetry/report.ts +21 -2
  64. package/src/telemetry/tools/git_events.ts +125 -0
  65. package/src/telemetry/tools/observations.ts +1 -1
  66. package/src/types.ts +3 -0
@@ -1,4 +1,5 @@
1
1
  import { randomUUID } from "node:crypto";
2
+ import { IMPORTED_ROUTER_NAME } from "../activity/imports.js";
2
3
  import { sqliteActivityDb } from "../activity/sql.js";
3
4
  import { canonicalInstant, instantFromDate } from "../activity/values.js";
4
5
  const MODEL_NAME_MAX_CHARS = 240;
@@ -9,6 +10,9 @@ const REASON_MAX_CHARS = 2000;
9
10
  const JSON_COLUMN_MAX_BYTES = 64 * 1024;
10
11
  // The blob "bucket" every retained body is filed under.
11
12
  export const SELF_HOSTED_BLOB_BUCKET = "gateway";
13
+ // The router imported requests are filed under; no config file serves it.
14
+ // A colon keeps it out of ROUTER_ID_PATTERN, so no configured router can take it.
15
+ const IMPORTED_ROUTER_ID = "dari:imported";
12
16
  const SCHEMA = `
13
17
  create table if not exists routing_requests (
14
18
  id text primary key,
@@ -159,6 +163,24 @@ create table if not exists users (
159
163
  email text not null,
160
164
  display_name text
161
165
  );
166
+ create table if not exists routing_git_events (
167
+ id text primary key,
168
+ organization_id text not null,
169
+ routing_request_id text references routing_requests (id) on delete cascade,
170
+ source_protocol text not null,
171
+ agent_session_id text not null,
172
+ occurred_at text not null,
173
+ ordinal integer not null,
174
+ kind text not null,
175
+ repository text not null,
176
+ number integer,
177
+ title text,
178
+ branch text,
179
+ commit_sha text
180
+ );
181
+ create index if not exists ix_routing_git_events_organization_session on routing_git_events (organization_id, agent_session_id);
182
+ create index if not exists ix_routing_git_events_organization_repository on routing_git_events (organization_id, repository);
183
+ create index if not exists ix_routing_git_events_routing_request_id on routing_git_events (routing_request_id);
162
184
  `;
163
185
  export class ActivityStore {
164
186
  db;
@@ -178,8 +200,8 @@ export class ActivityStore {
178
200
  syncDirectory(organizationId, routers, gatewayKeyCount) {
179
201
  this.db.transaction(() => {
180
202
  const now = canonicalInstant(instantFromDate(new Date()));
181
- this.db.query("update model_routers set deleted_at = coalesce(deleted_at, ?) where organization_id = ?")
182
- .run(now, organizationId);
203
+ this.db.query("update model_routers set deleted_at = coalesce(deleted_at, ?) where organization_id = ? and id <> ?")
204
+ .run(now, organizationId, IMPORTED_ROUTER_ID);
183
205
  for (const router of routers) {
184
206
  this.db.query(`insert into model_routers (id, organization_id, name, zdr, deleted_at) values (?, ?, ?, ?, null)
185
207
  on conflict (id) do update set name = excluded.name, zdr = excluded.zdr, deleted_at = null`).run(router.id, organizationId, router.id, router.zdr ? 1 : 0);
@@ -190,11 +212,23 @@ export class ActivityStore {
190
212
  }
191
213
  })();
192
214
  }
193
- /** Store one served request's report: its row, tool events, and bodies. */
215
+ /**
216
+ * Store one imported request's report under the "Imported" router, adding
217
+ * the router when Activity has none. False when the request is stored
218
+ * already.
219
+ */
220
+ importRequest(organizationId, report) {
221
+ this.db.query("insert into model_routers (id, organization_id, name) values (?, ?, ?) on conflict (id) do nothing").run(IMPORTED_ROUTER_ID, organizationId, IMPORTED_ROUTER_NAME);
222
+ return this.record({ ...report, organization_id: organizationId, router_id: IMPORTED_ROUTER_ID });
223
+ }
224
+ /**
225
+ * Store one served request's report: its row, tool events, and bodies.
226
+ * False when a request with its ID is stored already.
227
+ */
194
228
  record(report) {
195
229
  const requestId = text(report.request_id);
196
230
  if (requestId === null)
197
- return;
231
+ return false;
198
232
  const zdr = report.zdr === true;
199
233
  const id = `rreq_${randomUUID().replaceAll("-", "")}`;
200
234
  const organizationId = text(report.organization_id) ?? "";
@@ -283,18 +317,18 @@ export class ActivityStore {
283
317
  metadata_json: json({ organization_id: organizationId, router_id: text(report.router_id), cost_source: "pi_registry" }),
284
318
  };
285
319
  const columns = Object.keys(row);
286
- this.db.transaction(() => {
320
+ return this.db.transaction(() => {
287
321
  // A repeated report of the same request keeps the first.
288
322
  const inserted = this.db.query(`insert into routing_requests (${columns.join(", ")}) values (${columns.map(() => "?").join(", ")})
289
323
  on conflict (request_id) do nothing`).run(...Object.values(row));
290
324
  if (inserted.changes === 0)
291
- return;
325
+ return false;
292
326
  for (const [kind, body] of Object.entries(bodies)) {
293
327
  if (body !== null)
294
328
  this.db.query("insert into routing_request_blobs (object_key, body) values (?, ?)").run(keys[kind], body);
295
329
  }
296
330
  if (zdr)
297
- return;
331
+ return true;
298
332
  for (const event of list(report.tool_skill_events)) {
299
333
  this.db.query(`insert into routing_tool_skill_events
300
334
  (id, routing_request_id, event_type, tool_call_id, exchange_context_hash, capability_id, observed_name, skill_version, evidence_source, ordinal)
@@ -304,8 +338,27 @@ export class ActivityStore {
304
338
  this.db.query(`insert into routing_tool_result_observations (id, routing_request_id, tool_call_id, exchange_context_hash, ordinal)
305
339
  values (?, ?, ?, ?, ?)`).run(`rtro_${randomUUID().replaceAll("-", "")}`, id, text(observation.tool_call_id), text(observation.exchange_context_hash), int(observation.ordinal));
306
340
  }
341
+ const sessionId = text(row.agent_session_id);
342
+ if (sessionId)
343
+ this.insertGitEvents(organizationId, text(row.source_protocol), sessionId, id, receivedAt, list(report.git_events));
344
+ return true;
307
345
  })();
308
346
  }
347
+ async saveSessionGitEvents(write) {
348
+ const known = new Set(this.db.query(`select commit_sha from routing_git_events
349
+ where organization_id = ? and agent_session_id = ? and kind = 'commit'`).all(write.organizationId, write.agentSessionId).map((row) => row.commit_sha));
350
+ this.insertGitEvents(write.organizationId, write.sourceProtocol, write.agentSessionId, null, canonicalInstant(instantFromDate(new Date())), write.events.filter((event) => !known.has(event.commit_sha)));
351
+ }
352
+ /** Store a session's git events: what a step's tool output showed, or commits its git hook reported. */
353
+ insertGitEvents(organizationId, sourceProtocol, agentSessionId, routingRequestId, occurredAt, events) {
354
+ for (const event of events.map(record)) {
355
+ if (event === null)
356
+ continue;
357
+ this.db.query(`insert into routing_git_events
358
+ (id, organization_id, routing_request_id, source_protocol, agent_session_id, occurred_at, ordinal, kind, repository, number, title, branch, commit_sha)
359
+ values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(`rge_${randomUUID().replaceAll("-", "")}`, organizationId, routingRequestId, sourceProtocol ?? "", agentSessionId, occurredAt, int(event.ordinal), text(event.kind), text(event.repository), int(event.number), text(event.title), text(event.branch), text(event.commit_sha));
360
+ }
361
+ }
309
362
  /** A retained body, or null. */
310
363
  readBlob(key) {
311
364
  const row = this.db.query("select body from routing_request_blobs where object_key = ?").get(key);
@@ -87,6 +87,8 @@ export function createSelfHostedPlatform(deps) {
87
87
  cacheReadTokens: summary.cache_read_tokens ?? 0,
88
88
  cacheWriteTokens: summary.cache_write_tokens ?? 0,
89
89
  status: summary.status,
90
+ costUsd: record.link.costUsd,
91
+ credentialId: record.link.credentialId,
90
92
  });
91
93
  }
92
94
  },
@@ -114,6 +116,7 @@ export function createSelfHostedPlatform(deps) {
114
116
  // it serves (`current`).
115
117
  activity: {
116
118
  db: deps.activity.reads,
119
+ saveSessionGitEvents: (write) => deps.activity.saveSessionGitEvents(write),
117
120
  async authorize(request, organizationRef) {
118
121
  let key;
119
122
  try {
@@ -132,6 +135,9 @@ export function createSelfHostedPlatform(deps) {
132
135
  async readBlob(bucket, key) {
133
136
  return bucket === SELF_HOSTED_BLOB_BUCKET ? deps.activity.readBlob(key) : null;
134
137
  },
138
+ async importRequest({ organizationId }, report) {
139
+ return deps.activity.importRequest(organizationId, report);
140
+ },
135
141
  },
136
142
  };
137
143
  }
@@ -32,11 +32,10 @@ export type SelfHostedResolverDeps = {
32
32
  * neither are left out. A coding agent with its own model list on the router
33
33
  * is served that list.
34
34
  *
35
- * A Dari Link token resolves only the default router, served on its grant's
36
- * subscriptions alone and never an API key. Its `enabled_models` are the
37
- * router's models a granted plan serves, and `link_models` adds every other
38
- * catalog model of those plans' providers, which a request may name
39
- * explicitly. A child token serves only its one model.
35
+ * A Dari Link token is served apart from any router, on its grant's plans and
36
+ * API keys alone: `dari/routing` chooses among every catalog model they
37
+ * serve, which a request may also name explicitly. It comes in on the default
38
+ * router's path. A child token serves only its models.
40
39
  */
41
40
  export declare function resolveSelfHostedRouter(deps: SelfHostedResolverDeps, request: ResolveRouterRequest): Promise<ResolvedRouter>;
42
41
  export declare function configuredProviderApiKey(deps: Pick<SelfHostedResolverDeps, "config" | "providerApiKey" | "env">, provider: string): Promise<string | undefined>;
@@ -23,11 +23,10 @@ export const SELF_HOSTED_USER_ID = "self-hosted";
23
23
  * neither are left out. A coding agent with its own model list on the router
24
24
  * is served that list.
25
25
  *
26
- * A Dari Link token resolves only the default router, served on its grant's
27
- * subscriptions alone and never an API key. Its `enabled_models` are the
28
- * router's models a granted plan serves, and `link_models` adds every other
29
- * catalog model of those plans' providers, which a request may name
30
- * explicitly. A child token serves only its one model.
26
+ * A Dari Link token is served apart from any router, on its grant's plans and
27
+ * API keys alone: `dari/routing` chooses among every catalog model they
28
+ * serve, which a request may also name explicitly. It comes in on the default
29
+ * router's path. A child token serves only its models.
31
30
  */
32
31
  export async function resolveSelfHostedRouter(deps, request) {
33
32
  const keyIndex = gatewayKeyIndex(deps.gatewayKeys, request.apiKey);
@@ -38,16 +37,17 @@ export async function resolveSelfHostedRouter(deps, request) {
38
37
  if (grant !== null && request.routerId !== DEFAULT_ROUTER_ALIAS) {
39
38
  throw new HttpError(403, "Dari Link tokens serve only the default router.", "permission_denied");
40
39
  }
41
- const router = servedRouter(deps, request.routerId);
42
- if (router === undefined) {
40
+ const router = grant === null ? servedRouter(deps, request.routerId) : undefined;
41
+ if (grant === null && router === undefined) {
43
42
  throw new HttpError(404, `Router ${request.routerId} is not configured on this gateway.`, "router_not_found");
44
43
  }
45
- const routed = routerModelsFor(router, request.clientHarness);
44
+ const routed = router === undefined ? [] : routerModelsFor(router, request.clientHarness);
46
45
  const granted = grant === null
47
46
  ? []
48
47
  : deps.subscriptions.withIds(grant.credentialIds);
49
48
  // A grant's API keys, by the provider or gateway each is a key for.
50
- const grantedKeys = new Map((grant === null ? [] : deps.links.keysWithIds(grant.credentialIds)).map((key) => [key.provider, key.apiKey]));
49
+ const grantKeys = grant === null ? [] : deps.links.keysWithIds(grant.credentialIds);
50
+ const grantedKeys = new Map(grantKeys.map((key) => [key.provider, key.apiKey]));
51
51
  const listed = grant === null ? routed : grantModels(grant, routed, granted, grantedKeys);
52
52
  const now = new Date();
53
53
  const servable = grant === null ? undefined : new Set(grant.credentialIds);
@@ -55,7 +55,7 @@ export async function resolveSelfHostedRouter(deps, request) {
55
55
  const exhausted = new Set();
56
56
  for (const provider of new Set(listed.map(modelProvider))) {
57
57
  // A grant uses the subscriptions its user chose, whatever the router allows.
58
- const subscription = router.subscriptions || grant !== null
58
+ const subscription = router?.subscriptions || grant !== null
59
59
  ? subscriptionProviderFor(provider, request.clientHarness)
60
60
  : null;
61
61
  const active = subscription === null
@@ -126,16 +126,13 @@ export async function resolveSelfHostedRouter(deps, request) {
126
126
  const missing = [...credentials].filter(([, credential]) => credential == null).map(([provider]) => provider);
127
127
  throw unavailableRouterError(request.routerId, exhausted, missing);
128
128
  }
129
- // `dari/routing` chooses among the router's own models; a grant may also
130
- // name any other catalog model its plans serve.
131
- const routedIds = new Set(routed.map((model) => model.id));
132
- const enabled = grant === null || grant.pins !== undefined ? models : models.filter((model) => routedIds.has(model.id));
133
129
  const resolved = {
134
- router_id: request.routerId,
130
+ // A grant's requests and prefix state are its own, apart from any router.
131
+ router_id: grant?.id ?? request.routerId,
135
132
  organization_id: SELF_HOSTED_ORGANIZATION_ID,
136
133
  api_key_id: grant === null ? `gateway_key_${keyIndex + 1}` : grant.id,
137
134
  attributed_user_id: SELF_HOSTED_USER_ID,
138
- enabled_models: enabled.map((model) => model.id),
135
+ enabled_models: models.map((model) => model.id),
139
136
  routing_listed: deps.autoRouting,
140
137
  provider_keys: {},
141
138
  provider_key_sources: {},
@@ -146,6 +143,7 @@ export async function resolveSelfHostedRouter(deps, request) {
146
143
  ? {}
147
144
  : {
148
145
  link_models: models.map((model) => model.id),
146
+ link_key_credential_ids: Object.fromEntries(grantKeys.map((key) => [key.provider, key.id])),
149
147
  link_key_gateways: Object.fromEntries([...grantedKeys.keys()].filter((provider) => gatewayFor(provider) !== undefined).map((gateway) => {
150
148
  const endpoint = deps.config.providers[gateway];
151
149
  return [gateway, endpoint === undefined ? null : { api: endpoint.api, base_url: endpoint.baseUrl }];
@@ -156,21 +154,21 @@ export async function resolveSelfHostedRouter(deps, request) {
156
154
  : grant.pins.map((pin) => ({ model: pin.model, thinking: isReasoningEffort(pin.thinking) ? pin.thinking : null })),
157
155
  link_tags: grant.tags ?? null,
158
156
  }),
159
- zdr: router.zdr,
157
+ zdr: router?.zdr ?? false,
160
158
  speculative_routing: false,
161
- session_pinning: router.sessionPinning,
162
- native_compaction: router.nativeCompaction,
163
- primary_retries: router.retries,
159
+ session_pinning: router?.sessionPinning ?? false,
160
+ native_compaction: router?.nativeCompaction ?? false,
161
+ ...(router === undefined ? {} : { primary_retries: router.retries }),
164
162
  routing_strategy: "dari",
165
163
  custom_config: null,
166
164
  // A grant's request is served the model it named, never a role's.
167
- ...(grant === null ? { role_models: router.roleModels, role_prompts: router.rolePrompts } : {}),
165
+ ...(router === undefined ? {} : { role_models: router.roleModels, role_prompts: router.rolePrompts }),
168
166
  evals: [],
169
167
  model_thinking_levels: thinkingLevels(listed),
170
168
  model_prices: {},
171
169
  model_configs: {},
172
170
  prefix_hits: deps.prefixHits({
173
- routerId: request.routerId,
171
+ routerId: grant?.id ?? request.routerId,
174
172
  prefixHashes: request.prefixHashes ?? [],
175
173
  ...(request.conversationId ? { conversationId: request.conversationId } : {}),
176
174
  }),
@@ -23,6 +23,7 @@ import { credentialRejectionFromFailure } from "../runtime/provider_stream_outco
23
23
  import { scrubSecrets } from "./scrub.js";
24
24
  import { encodeRetainedInteractionRequest } from "./requests/retained_interaction_request.js";
25
25
  import { toolResultObservations, toolSkillEvents } from "./tools/observations.js";
26
+ import { gitEvents } from "./tools/git_events.js";
26
27
  // Log pipelines commonly cap entries at 256 KB and split longer stdout lines
27
28
  // into fragments; one guard keeps pathological provider errors
28
29
  // (request-payload echoes) from mangling log entries.
@@ -325,11 +326,18 @@ export class RequestReporter {
325
326
  });
326
327
  trackBackgroundTelemetry(this.prefixStatePromise);
327
328
  }
328
- // A Dari Link request's usage is readable back by its app.
329
+ // A Dari Link request's usage is readable back by its app, and its cost
330
+ // counts toward the plan or key that served it (a plan's at API prices).
329
331
  const link = a.credentials.link_grant_id
330
332
  ? {
331
333
  grantId: a.credentials.link_grant_id,
332
334
  thinking: outcome.providerExecution?.thinkingLevel ?? reasoningBucket,
335
+ costUsd: costSource === null || !isRecord(usage?.cost) ? null : finiteNumber(usage.cost.total),
336
+ credentialId: keySource === "subscription"
337
+ ? outcome.providerExecution?.subscriptionCredentialId ?? (selectedProvider
338
+ ? a.credentials.subscription_credential_ids?.[selectedProvider] ?? null
339
+ : null)
340
+ : selectedProvider ? a.credentials.link_key_credential_ids?.[selectedProvider] ?? null : null,
333
341
  }
334
342
  : undefined;
335
343
  const ingestPayload = {
@@ -422,9 +430,20 @@ export class RequestReporter {
422
430
  request: a.interaction,
423
431
  zdr: a.zdr,
424
432
  }),
433
+ git_events: gitEvents(a.interaction, a.zdr),
425
434
  prefix_entry: prefixEntry,
426
435
  touched_prefix_hash: touchedHash,
427
- ...(link === undefined ? {} : { link: { grant_id: link.grantId, thinking: link.thinking, tags: a.tags } }),
436
+ ...(link === undefined
437
+ ? {}
438
+ : {
439
+ link: {
440
+ grant_id: link.grantId,
441
+ thinking: link.thinking,
442
+ tags: a.tags,
443
+ cost_usd: link.costUsd,
444
+ credential_id: link.credentialId,
445
+ },
446
+ }),
428
447
  };
429
448
  gatewayPlatform().recordRequest({
430
449
  ...(link === undefined ? {} : { link }),
@@ -0,0 +1,36 @@
1
+ import type { InteractionRequest } from "../../interaction/types.js";
2
+ type Fields = {
3
+ repository: string;
4
+ ordinal: number;
5
+ };
6
+ export type GitEventReport = Fields & {
7
+ kind: "opened";
8
+ number: number;
9
+ title: string | null;
10
+ branch: string | null;
11
+ } | Fields & {
12
+ kind: "referenced";
13
+ number: number;
14
+ title: null;
15
+ branch: null;
16
+ } | Fields & {
17
+ kind: "push";
18
+ number: null;
19
+ title: null;
20
+ branch: string;
21
+ };
22
+ /** A commit made in an agent session, with its branch's open pull request when the hook found one. */
23
+ export type CommitEvent = {
24
+ kind: "commit";
25
+ repository: string;
26
+ branch: string;
27
+ commit_sha: string;
28
+ number: number | null;
29
+ title: string | null;
30
+ ordinal: number;
31
+ };
32
+ /** The GitHub pull requests and pushes in the request's newly submitted tool results. */
33
+ export declare function gitEvents(request: InteractionRequest, zdr: boolean): GitEventReport[];
34
+ /** The GitHub pull requests and pushes in every tool result of a request, as a stored request is read. */
35
+ export declare function allGitEvents(request: InteractionRequest): GitEventReport[];
36
+ export {};
@@ -0,0 +1,109 @@
1
+ /* Pull requests and pushes an agent made, read from its own tool output:
2
+ a `gh pr create` result prints the new pull request's URL, other `gh pr`
3
+ commands name the pull request they work on, and a `git push` result names
4
+ the GitHub repository and the branches it updated. Activity links each
5
+ agent session to the pull requests it opened or worked on, and to those
6
+ whose branch it pushed or committed to (commits arrive from the Dari CLI's
7
+ git hook, `ingress/git_events.ts`). Only GitHub is recognized. */
8
+ import { newlySubmittedToolResults } from "./observations.js";
9
+ const MAX_EVENTS = 50;
10
+ const MAX_TITLE_CHARS = 300;
11
+ const PULL_REQUEST_URL = /https:\/\/github\.com\/([\w.-]+)\/([\w.-]+)\/pull\/(\d+)\b/g;
12
+ // GitHub's reply to the first push of a branch: `remote: https://github.com/owner/repo/pull/new/branch`.
13
+ const NEW_BRANCH_URL = /github\.com\/([\w.-]+)\/([\w.-]+)\/pull\/new\/(\S+)/g;
14
+ // `gh pr` commands that work on one pull request, unlike `list` or `api` which print many.
15
+ const WORKS_ON_PULL_REQUEST = /\bgh\s+pr\s+(?:view|checks|merge|comment|edit|diff|ready|review|close|reopen|checkout|update-branch)\b/;
16
+ // `To github.com:owner/repo.git`, `To git@github.com:owner/repo.git`, `To https://github.com/owner/repo`, or `To ssh://git@github.com/owner/repo.git`.
17
+ const PUSH_DESTINATION = /^To\s+(?:https:\/\/(?:[^@/\s]+@)?github\.com\/|(?:ssh:\/\/)?(?:git@)?github\.com[:/])([\w.-]+)\/([\w.-]+?)(?:\.git)?\/?\s*$/;
18
+ // ` 1a2b..3c4d local -> remote`, ` + 1a2b...3c4d local -> remote (forced update)`, ` * [new branch] local -> remote`.
19
+ const PUSHED_REF = /^\s*[+* ]?\s*(?:[0-9a-f]+\.\.\.?[0-9a-f]+|\[new branch\])\s+\S+\s+->\s+(\S+)/;
20
+ const TITLE = /(?:--title|-t)(?:=|\s+)(?:"((?:[^"\\]|\\.)*)"|'([^']*)'|(\S+))/;
21
+ const HEAD = /--head(?:=|\s+)["']?([^\s"']+)/;
22
+ /** The GitHub pull requests and pushes in the request's newly submitted tool results. */
23
+ export function gitEvents(request, zdr) {
24
+ if (zdr)
25
+ return [];
26
+ return gitEventsIn(request.items, newlySubmittedToolResults(request).results.map(({ ordinal }) => ordinal));
27
+ }
28
+ /** The GitHub pull requests and pushes in every tool result of a request, as a stored request is read. */
29
+ export function allGitEvents(request) {
30
+ return gitEventsIn(request.items, request.items.flatMap((item, ordinal) => (item.type === "tool_result" ? [ordinal] : [])));
31
+ }
32
+ function gitEventsIn(items, resultOrdinals) {
33
+ const calls = new Map();
34
+ for (const item of items) {
35
+ if (item.type === "tool_call") {
36
+ calls.set(item.callId, `${item.name} ${typeof item.input === "string" ? item.input : JSON.stringify(item.input ?? {})}`);
37
+ }
38
+ }
39
+ const events = [];
40
+ for (const ordinal of resultOrdinals) {
41
+ const result = items[ordinal];
42
+ if (result?.type !== "tool_result" || result.isError)
43
+ continue;
44
+ const call = calls.get(result.callId);
45
+ if (call === undefined)
46
+ continue;
47
+ const output = outputText(result.output);
48
+ const pushed = [];
49
+ if (/\bgit\s+(?:-C\s+\S+\s+)?push\b/.test(call)) {
50
+ let repository = null;
51
+ for (const line of output.split(/\r?\n/)) {
52
+ const destination = PUSH_DESTINATION.exec(line);
53
+ if (destination !== null) {
54
+ repository = `${destination[1]}/${destination[2]}`.toLowerCase();
55
+ continue;
56
+ }
57
+ const ref = repository === null ? null : PUSHED_REF.exec(line);
58
+ if (ref !== null && repository !== null)
59
+ pushed.push({ repository, branch: ref[1].replace(/^refs\/heads\//, "") });
60
+ }
61
+ for (const [, owner, repo, branch] of output.matchAll(NEW_BRANCH_URL)) {
62
+ pushed.push({ repository: `${owner}/${repo}`.toLowerCase(), branch: branch });
63
+ }
64
+ }
65
+ for (const push of pushed) {
66
+ if (!push.branch.startsWith("refs/"))
67
+ events.push({ kind: "push", ...push, number: null, title: null, ordinal });
68
+ }
69
+ const opened = /\bgh\s+pr\s+create\b/.test(call) || /create_pull_request/i.test(call);
70
+ if (opened) {
71
+ const title = titleOf(call);
72
+ for (const [, owner, repo, number] of output.matchAll(PULL_REQUEST_URL)) {
73
+ const repository = `${owner}/${repo}`.toLowerCase();
74
+ const branch = HEAD.exec(call)?.[1] ?? [...pushed].reverse().find((push) => push.repository === repository)?.branch ?? null;
75
+ events.push({ kind: "opened", repository, number: Number(number), title, branch, ordinal });
76
+ }
77
+ }
78
+ else if (WORKS_ON_PULL_REQUEST.test(call)) {
79
+ for (const [, owner, repo, number] of `${call}\n${output}`.matchAll(PULL_REQUEST_URL)) {
80
+ events.push({ kind: "referenced", repository: `${owner}/${repo}`.toLowerCase(), number: Number(number), title: null, branch: null, ordinal });
81
+ }
82
+ }
83
+ }
84
+ // One event per pull request or branch per result.
85
+ const seen = new Set();
86
+ return events.filter((event) => {
87
+ const key = JSON.stringify([event.ordinal, event.kind, event.repository, event.number, event.branch]);
88
+ if (seen.has(key))
89
+ return false;
90
+ seen.add(key);
91
+ return true;
92
+ }).slice(0, MAX_EVENTS);
93
+ }
94
+ function outputText(output) {
95
+ if (output === null)
96
+ return "";
97
+ if (typeof output === "string")
98
+ return output;
99
+ return output.map((part) => (part.type === "text" ? part.text : "")).join("\n");
100
+ }
101
+ /** The `--title` a `gh pr create` command passed, when it passed one plainly. */
102
+ function titleOf(call) {
103
+ // A command inside a JSON input arrives with its quotes escaped.
104
+ const match = TITLE.exec(call.replaceAll('\\"', '"'));
105
+ const title = match?.[1] ?? match?.[2] ?? match?.[3];
106
+ if (title === undefined || title.includes("$("))
107
+ return null;
108
+ return title.replaceAll('\\"', '"').trim().slice(0, MAX_TITLE_CHARS) || null;
109
+ }
@@ -1,4 +1,4 @@
1
- import type { InteractionOutput, InteractionRequest } from "../../interaction/types.js";
1
+ import type { InteractionOutput, InteractionRequest, InteractionToolResult } from "../../interaction/types.js";
2
2
  import type { HarnessConversationIdentity } from "../../runtime/harness_identity/index.js";
3
3
  export type ToolSkillEventReport = {
4
4
  event_type: "tool_call" | "skill_use" | "skill_load";
@@ -27,3 +27,10 @@ export declare function toolResultObservations(args: {
27
27
  request: InteractionRequest;
28
28
  zdr: boolean;
29
29
  }): ToolResultObservationReport[];
30
+ export declare function newlySubmittedToolResults(request: InteractionRequest): {
31
+ results: Array<{
32
+ item: InteractionToolResult;
33
+ ordinal: number;
34
+ }>;
35
+ contextEnd: number;
36
+ };
@@ -97,7 +97,7 @@ export function toolResultObservations(args) {
97
97
  ordinal,
98
98
  }));
99
99
  }
100
- function newlySubmittedToolResults(request) {
100
+ export function newlySubmittedToolResults(request) {
101
101
  if (request.sourceProtocol === "anthropic_messages") {
102
102
  return currentAnthropicUserTurnResults(request.items);
103
103
  }
package/dist/types.d.ts CHANGED
@@ -84,6 +84,7 @@ export type ResolvedRouter = {
84
84
  provider_key_sources?: Partial<Record<Provider, ProviderKeySource>>;
85
85
  provider_credentials?: Record<string, ProviderCredential>;
86
86
  subscription_credential_ids?: Partial<Record<Provider, string>>;
87
+ link_key_credential_ids?: Partial<Record<Provider, string>>;
87
88
  link_grant_id?: string | null;
88
89
  link_models?: string[];
89
90
  link_unavailable?: Record<string, LinkUnavailable>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mupt-ai/dari-gateway",
3
- "version": "1.0.334",
3
+ "version": "1.0.335",
4
4
  "description": "Self-hostable LLM gateway for coding agents and APIs: one endpoint for Anthropic Messages, OpenAI Chat Completions, and OpenAI Responses, with subscription pooling, failover, and prompt-cache-aware routing.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -52,7 +52,7 @@
52
52
  },
53
53
  "dependencies": {
54
54
  "@aws-sdk/client-sts": "3.1063.0",
55
- "@mupt-ai/dari-router": "1.0.334",
55
+ "@mupt-ai/dari-router": "1.0.335",
56
56
  "@mupt-ai/pi-ai": "1.5.2-mupt.3"
57
57
  },
58
58
  "devDependencies": {
@@ -22,6 +22,7 @@ import {
22
22
  import type { SourceProtocol } from "./filters.js";
23
23
  import type { ActivityRoute } from "./http.js";
24
24
  import { notFound } from "./params.js";
25
+ import { sessionCommits, withPullRequests } from "./pull_requests.js";
25
26
  import { thinkingLevelValue } from "./shared.js";
26
27
  import { sql, type ActivityDb } from "./sql.js";
27
28
  import { formatInstant, readOptionalString } from "./values.js";
@@ -152,8 +153,10 @@ export const conversation: ActivityRoute = async (request) => {
152
153
  route_path: routePath(records),
153
154
  }));
154
155
  const hasMore = start > 0;
156
+ const [summary] = await withPullRequests(db, organizationId, [conversationSummary(all, entities, undefined, null)]);
155
157
  return {
156
- conversation: conversationSummary(all, entities, undefined, null),
158
+ conversation: summary!,
159
+ commits: await sessionCommits(db, organizationId, summary!.source_protocol, summary!.agent_session_id),
157
160
  streams,
158
161
  filtered_model_steps: filtered.length,
159
162
  focused_request_class: focusedRequestClass,
@@ -19,6 +19,7 @@ import {
19
19
  import { criteria, readActivityQuery, readSourceScope, sourceProtocols, validatedFilters } from "./filters.js";
20
20
  import type { ActivityRoute } from "./http.js";
21
21
  import { notFound } from "./params.js";
22
+ import { withPullRequests } from "./pull_requests.js";
22
23
  import { AGENT_SESSION_KEY } from "./shared.js";
23
24
  import { likePattern, raw, sql } from "./sql.js";
24
25
  import { readInt, readOptionalString } from "./values.js";
@@ -164,7 +165,7 @@ export const conversations: ActivityRoute = async (request) => {
164
165
  keys = keys.slice(0, limit);
165
166
  nextOffset = offset + limit;
166
167
  }
167
- const items: object[] = [];
168
+ const items: Array<ReturnType<typeof conversationSummary>> = [];
168
169
  if (keys.length > 0) {
169
170
  const [records, titles] = await Promise.all([
170
171
  loadRecords(db, sql`${where} and ${groupsCondition(keys)}`),
@@ -182,7 +183,7 @@ export const conversations: ActivityRoute = async (request) => {
182
183
  }
183
184
  }
184
185
  return {
185
- conversations: items,
186
+ conversations: await withPullRequests(db, organizationId, items),
186
187
  conversation_count: readInt(totals.conversation_count),
187
188
  model_switches: readInt(totals.total_model_switches),
188
189
  conversations_with_model_switches: readInt(totals.conversations_with_model_switches),