@kwirthmagnify/kwirth-common-ai 0.5.26 → 0.5.28

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.
package/dist/back.d.ts CHANGED
@@ -7,12 +7,19 @@ export declare const loadModels: (providers: ILlmProvider[], log: IBackChannelOb
7
7
  export { generateText, Output, stepCountIs, tool } from 'ai';
8
8
  export { z } from 'zod';
9
9
  export declare const zodFromExample: (example: Record<string, unknown>) => z.ZodObject<Record<string, z.ZodTypeAny>>;
10
+ export interface ISourceRepoCred {
11
+ host: string;
12
+ type: 'github' | 'gitlab';
13
+ token: string;
14
+ apiBaseUrl?: string;
15
+ }
10
16
  export interface IToolContext {
11
17
  origin: string;
12
18
  nodes: Map<string, any>;
13
19
  clusterInfo: any;
14
20
  clusterMetrics: any[];
15
21
  clusterEvents?: any[];
22
+ sourceRepos?: ISourceRepoCred[];
16
23
  trace: (toolName: string, args: Record<string, unknown>) => void;
17
24
  }
18
25
  export declare enum EToolEffect {
@@ -368,6 +375,11 @@ export declare const tools: {
368
375
  startTime: any;
369
376
  reason: any;
370
377
  message: any;
378
+ controlledBy: any;
379
+ source: {
380
+ repo: any;
381
+ revision: any;
382
+ } | undefined;
371
383
  conditions: any;
372
384
  containers: any;
373
385
  initContainers: any;
@@ -385,6 +397,8 @@ export declare const tools: {
385
397
  startTime?: undefined;
386
398
  reason?: undefined;
387
399
  message?: undefined;
400
+ controlledBy?: undefined;
401
+ source?: undefined;
388
402
  conditions?: undefined;
389
403
  containers?: undefined;
390
404
  initContainers?: undefined;
@@ -398,6 +412,41 @@ export declare const tools: {
398
412
  namespace: string;
399
413
  name: string;
400
414
  }, any>;
415
+ readonly get_rollout_history: import("ai").Tool<{
416
+ namespace: string;
417
+ name: string;
418
+ }, {
419
+ deployment: string;
420
+ namespace: string;
421
+ revisionCount: any;
422
+ revisions: any;
423
+ error?: undefined;
424
+ } | {
425
+ error: any;
426
+ deployment?: undefined;
427
+ namespace?: undefined;
428
+ revisionCount?: undefined;
429
+ revisions?: undefined;
430
+ }>;
431
+ readonly get_source_file: import("ai").Tool<{
432
+ repo: string;
433
+ ref: string;
434
+ path: string;
435
+ }, {
436
+ repo: string;
437
+ ref: string;
438
+ path: string;
439
+ truncated: boolean;
440
+ content: string;
441
+ error?: undefined;
442
+ } | {
443
+ error: any;
444
+ repo?: undefined;
445
+ ref?: undefined;
446
+ path?: undefined;
447
+ truncated?: undefined;
448
+ content?: undefined;
449
+ }>;
401
450
  };
402
451
  export declare const toolInfoList: IToolInfo[];
403
452
  export interface IAgentRunResult {
package/dist/back.js CHANGED
@@ -174,6 +174,37 @@ const zodFromExample = (example) => {
174
174
  return zod_1.z.object(shape);
175
175
  };
176
176
  exports.zodFromExample = zodFromExample;
177
+ // Parse a repo reference (full URL or 'owner/name'; bare form assumes github.com). Owner keeps GitLab subgroups.
178
+ const parseRepoRef = (repo) => {
179
+ let host = 'github.com';
180
+ let pathPart = repo.trim();
181
+ const m = pathPart.match(/^(?:git@|https?:\/\/)?([^/:]+)[/:](.+)$/);
182
+ if (m && m[1].includes('.')) {
183
+ host = m[1];
184
+ pathPart = m[2];
185
+ }
186
+ const projectPath = pathPart.replace(/\.git$/, '').replace(/^\/+|\/+$/g, '');
187
+ return { host, projectPath };
188
+ };
189
+ // Fetch one file's raw content at a ref from GitHub or GitLab (cloud or on-prem), using the matching cred.
190
+ const fetchSourceFile = async (cred, projectPath, ref, path) => {
191
+ var _a, _b;
192
+ const cleanPath = path.replace(/^\/+/, '');
193
+ if (cred.type === 'github') {
194
+ const base = (_a = cred.apiBaseUrl) !== null && _a !== void 0 ? _a : 'https://api.github.com';
195
+ const url = `${base}/repos/${projectPath}/contents/${cleanPath.split('/').map(encodeURIComponent).join('/')}?ref=${encodeURIComponent(ref)}`;
196
+ const resp = await fetch(url, { headers: { Authorization: `Bearer ${cred.token}`, Accept: 'application/vnd.github.raw', 'User-Agent': 'kwirth-agora' } });
197
+ if (!resp.ok)
198
+ throw new Error(`GitHub ${resp.status} for ${projectPath}/${cleanPath}@${ref}`);
199
+ return await resp.text();
200
+ }
201
+ const base = (_b = cred.apiBaseUrl) !== null && _b !== void 0 ? _b : `https://${cred.host}/api/v4`;
202
+ const url = `${base}/projects/${encodeURIComponent(projectPath)}/repository/files/${encodeURIComponent(cleanPath)}/raw?ref=${encodeURIComponent(ref)}`;
203
+ const resp = await fetch(url, { headers: { 'PRIVATE-TOKEN': cred.token, 'User-Agent': 'kwirth-agora' } });
204
+ if (!resp.ok)
205
+ throw new Error(`GitLab ${resp.status} for ${projectPath}/${cleanPath}@${ref}`);
206
+ return await resp.text();
207
+ };
177
208
  // Effect of a tool: READ (safe, informational) or WRITE (has side effects on the cluster).
178
209
  // Dual purpose: hints the LLM, and gates authorization (Agora/readOnly filter out WRITE).
179
210
  var EToolEffect;
@@ -786,32 +817,57 @@ exports.tools = {
786
817
  name: zod_1.z.string().describe('Name of the pod')
787
818
  }),
788
819
  execute: async ({ namespace, name }) => {
789
- var _a, _b, _c, _d, _e, _f, _g;
820
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q;
790
821
  ctx().trace('describe_pod', { namespace, name });
791
822
  try {
792
- const pod = await ctx().clusterInfo.coreApi.readNamespacedPod({ name, namespace });
823
+ const c = ctx().clusterInfo;
824
+ const pod = await c.coreApi.readNamespacedPod({ name, namespace });
793
825
  const spec = (_a = pod.spec) !== null && _a !== void 0 ? _a : {}, status = (_b = pod.status) !== null && _b !== void 0 ? _b : {};
826
+ // image = the tag (spec); imageID = the resolved digest (catches a mutable tag repushed with a broken build).
794
827
  const containerStatus = (cs) => {
795
828
  var _a, _b, _c, _d;
796
829
  return ({
797
- name: cs.name, image: cs.image, ready: cs.ready, restartCount: cs.restartCount,
830
+ name: cs.name, image: cs.image, imageID: cs.imageID, ready: cs.ready, restartCount: cs.restartCount,
798
831
  state: ((_a = cs.state) === null || _a === void 0 ? void 0 : _a.waiting) ? { waiting: { reason: cs.state.waiting.reason, message: cs.state.waiting.message } }
799
832
  : ((_b = cs.state) === null || _b === void 0 ? void 0 : _b.terminated) ? { terminated: { reason: cs.state.terminated.reason, exitCode: cs.state.terminated.exitCode } }
800
833
  : ((_c = cs.state) === null || _c === void 0 ? void 0 : _c.running) ? { running: { startedAt: cs.state.running.startedAt } } : cs.state,
801
834
  lastTerminated: ((_d = cs.lastState) === null || _d === void 0 ? void 0 : _d.terminated) ? { reason: cs.lastState.terminated.reason, exitCode: cs.lastState.terminated.exitCode, signal: cs.lastState.terminated.signal, finishedAt: cs.lastState.terminated.finishedAt } : undefined
802
835
  });
803
836
  };
804
- const specContainer = (c) => ({ name: c.name, image: c.image, resources: c.resources, livenessProbe: !!c.livenessProbe, readinessProbe: !!c.readinessProbe, startupProbe: !!c.startupProbe });
837
+ const specContainer = (ct) => ({ name: ct.name, image: ct.image, resources: ct.resources, livenessProbe: !!ct.livenessProbe, readinessProbe: !!ct.readinessProbe, startupProbe: !!ct.startupProbe });
838
+ // Resolve the owning controller (pod → ReplicaSet → Deployment) so the bot can call get_rollout_history directly.
839
+ let controlledBy = undefined;
840
+ const podOwner = ((_d = (_c = pod.metadata) === null || _c === void 0 ? void 0 : _c.ownerReferences) !== null && _d !== void 0 ? _d : [])[0];
841
+ if ((podOwner === null || podOwner === void 0 ? void 0 : podOwner.kind) === 'ReplicaSet') {
842
+ try {
843
+ const rs = await c.appsApi.readNamespacedReplicaSet({ name: podOwner.name, namespace });
844
+ const rsOwner = ((_f = (_e = rs.metadata) === null || _e === void 0 ? void 0 : _e.ownerReferences) !== null && _f !== void 0 ? _f : [])[0];
845
+ controlledBy = rsOwner ? { kind: rsOwner.kind, name: rsOwner.name } : { kind: 'ReplicaSet', name: podOwner.name };
846
+ }
847
+ catch (_r) {
848
+ controlledBy = { kind: 'ReplicaSet', name: podOwner.name };
849
+ }
850
+ }
851
+ else if (podOwner) {
852
+ controlledBy = { kind: podOwner.kind, name: podOwner.name }; // StatefulSet/DaemonSet/Job own pods directly
853
+ }
854
+ // Source provenance: OCI standard annotations (org.opencontainers.image.*) with a kwirth.io fallback →
855
+ // the repo + commit the image was built from, so the bot can read the actual source (get_source_file).
856
+ const ann = (_h = (_g = pod.metadata) === null || _g === void 0 ? void 0 : _g.annotations) !== null && _h !== void 0 ? _h : {};
857
+ const sourceRepo = (_j = ann['org.opencontainers.image.source']) !== null && _j !== void 0 ? _j : ann['kwirth.io/source-repo'];
858
+ const source = sourceRepo ? { repo: sourceRepo, revision: (_k = ann['org.opencontainers.image.revision']) !== null && _k !== void 0 ? _k : ann['kwirth.io/source-ref'] } : undefined;
805
859
  return {
806
860
  name, namespace, phase: status.phase, node: spec.nodeName, startTime: status.startTime, reason: status.reason, message: status.message,
807
- conditions: ((_c = status.conditions) !== null && _c !== void 0 ? _c : []).map((c) => ({ type: c.type, status: c.status, reason: c.reason })),
808
- containers: ((_d = status.containerStatuses) !== null && _d !== void 0 ? _d : []).map(containerStatus),
809
- initContainers: ((_e = status.initContainerStatuses) !== null && _e !== void 0 ? _e : []).map(containerStatus),
810
- spec: { containers: ((_f = spec.containers) !== null && _f !== void 0 ? _f : []).map(specContainer), restartPolicy: spec.restartPolicy }
861
+ controlledBy, // e.g. { kind: 'Deployment', name: 'montag-agent' } → feed to get_rollout_history
862
+ source, // { repo, revision } from image annotations → feed to get_source_file
863
+ conditions: ((_l = status.conditions) !== null && _l !== void 0 ? _l : []).map((c) => ({ type: c.type, status: c.status, reason: c.reason })),
864
+ containers: ((_m = status.containerStatuses) !== null && _m !== void 0 ? _m : []).map(containerStatus),
865
+ initContainers: ((_o = status.initContainerStatuses) !== null && _o !== void 0 ? _o : []).map(containerStatus),
866
+ spec: { containers: ((_p = spec.containers) !== null && _p !== void 0 ? _p : []).map(specContainer), restartPolicy: spec.restartPolicy }
811
867
  };
812
868
  }
813
869
  catch (err) {
814
- return { error: (_g = err.message) !== null && _g !== void 0 ? _g : String(err) };
870
+ return { error: (_q = err.message) !== null && _q !== void 0 ? _q : String(err) };
815
871
  }
816
872
  }
817
873
  }),
@@ -849,6 +905,64 @@ exports.tools = {
849
905
  }
850
906
  }
851
907
  }),
908
+ get_rollout_history: (0, ai_1.tool)({
909
+ description: 'Returns the rollout history (revisions) of a Deployment via its ReplicaSets: per revision the image(s), replicas and pod-template summary (env names, resources, command). Use to see WHAT CHANGED recently — a new image tag, a changed env/resource/command — that may have broken the pods (the "artifact versions" of the workload). Compare the newest revision against the previous one.',
910
+ inputSchema: zod_1.z.object({
911
+ namespace: zod_1.z.string().describe('Namespace of the deployment'),
912
+ name: zod_1.z.string().describe('Name of the Deployment (the owning workload, e.g. describe_pod.controlledBy.name — NOT the pod name)')
913
+ }),
914
+ execute: async ({ namespace, name }) => {
915
+ var _a, _b;
916
+ ctx().trace('get_rollout_history', { namespace, name });
917
+ try {
918
+ const rsList = await ctx().clusterInfo.appsApi.listNamespacedReplicaSet({ namespace });
919
+ const owned = ((_a = rsList.items) !== null && _a !== void 0 ? _a : []).filter((rs) => { var _a, _b; return ((_b = (_a = rs.metadata) === null || _a === void 0 ? void 0 : _a.ownerReferences) !== null && _b !== void 0 ? _b : []).some((o) => o.kind === 'Deployment' && o.name === name); });
920
+ const container = (ct) => { var _a; return ({ name: ct.name, image: ct.image, command: ct.command, args: ct.args, resources: ct.resources, env: ((_a = ct.env) !== null && _a !== void 0 ? _a : []).map((e) => e.name) }); };
921
+ const revisions = owned.map((rs) => {
922
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o;
923
+ const tmpl = (_c = (_b = (_a = rs.spec) === null || _a === void 0 ? void 0 : _a.template) === null || _b === void 0 ? void 0 : _b.spec) !== null && _c !== void 0 ? _c : {};
924
+ return {
925
+ revision: Number((_f = (_e = (_d = rs.metadata) === null || _d === void 0 ? void 0 : _d.annotations) === null || _e === void 0 ? void 0 : _e['deployment.kubernetes.io/revision']) !== null && _f !== void 0 ? _f : 0),
926
+ replicaSet: (_g = rs.metadata) === null || _g === void 0 ? void 0 : _g.name,
927
+ createdAt: (_h = rs.metadata) === null || _h === void 0 ? void 0 : _h.creationTimestamp,
928
+ replicas: (_k = (_j = rs.spec) === null || _j === void 0 ? void 0 : _j.replicas) !== null && _k !== void 0 ? _k : 0,
929
+ readyReplicas: (_m = (_l = rs.status) === null || _l === void 0 ? void 0 : _l.readyReplicas) !== null && _m !== void 0 ? _m : 0,
930
+ containers: ((_o = tmpl.containers) !== null && _o !== void 0 ? _o : []).map(container),
931
+ serviceAccount: tmpl.serviceAccountName,
932
+ securityContext: tmpl.securityContext
933
+ };
934
+ }).sort((a, b) => b.revision - a.revision); // newest first
935
+ return { deployment: name, namespace, revisionCount: revisions.length, revisions };
936
+ }
937
+ catch (err) {
938
+ return { error: (_b = err.message) !== null && _b !== void 0 ? _b : String(err) };
939
+ }
940
+ }
941
+ }),
942
+ get_source_file: (0, ai_1.tool)({
943
+ description: 'Fetches the contents of a single source file from a Git repository (GitHub or GitLab) at a specific ref. Use to inspect the actual source behind a crash: read the stack-trace file:line from the logs, then fetch that file at the image build revision (describe_pod.source). Call repeatedly to follow the trace across files until you find the bug.',
944
+ inputSchema: zod_1.z.object({
945
+ repo: zod_1.z.string().describe('Repository URL or owner/name (e.g. https://github.com/org/app or org/app) — from describe_pod.source.repo'),
946
+ ref: zod_1.z.string().describe('Commit SHA, branch or tag — use the build revision (describe_pod.source.revision) so you read the code actually running'),
947
+ path: zod_1.z.string().describe('File path within the repo (e.g. src/regex/loader.go)')
948
+ }),
949
+ execute: async ({ repo, ref, path }) => {
950
+ var _a, _b;
951
+ ctx().trace('get_source_file', { repo, ref, path });
952
+ try {
953
+ const { host, projectPath } = parseRepoRef(repo);
954
+ const cred = ((_a = ctx().sourceRepos) !== null && _a !== void 0 ? _a : []).find(r => r.host === host);
955
+ if (!cred)
956
+ return { error: `No source-repo credentials configured for host '${host}'. Add it in Agora → Source repos.` };
957
+ const text = await fetchSourceFile(cred, projectPath, ref, path);
958
+ const truncated = text.length > 20000;
959
+ return { repo: projectPath, ref, path, truncated, content: truncated ? text.slice(0, 20000) : text };
960
+ }
961
+ catch (err) {
962
+ return { error: (_b = err.message) !== null && _b !== void 0 ? _b : String(err) };
963
+ }
964
+ }
965
+ }),
852
966
  };
853
967
  exports.toolInfoList = [
854
968
  { name: 'list_namespaces', effect: EToolEffect.READ, description: 'Lists all namespaces in the cluster with their status and labels.' },
@@ -882,6 +996,8 @@ exports.toolInfoList = [
882
996
  { name: 'describe_pod', effect: EToolEffect.READ, description: 'Diagnostic summary of a pod (kubectl describe pod): per-container waiting/terminated reason + exitCode (OOMKilled/CrashLoop…), restart count, probes.' },
883
997
  { name: 'get_pod_yaml', effect: EToolEffect.READ, description: 'Full Pod manifest (kubectl get pod -o yaml): spec (env, volumes, resources, probes) and status.' },
884
998
  { name: 'get_deployment_yaml', effect: EToolEffect.READ, description: 'Full Deployment manifest (kubectl get deployment -o yaml): pod template (image, env, resources, probes) and strategy.' },
999
+ { name: 'get_rollout_history', effect: EToolEffect.READ, description: 'Rollout revisions of a Deployment (via ReplicaSets): image + template per revision, to see what changed (new image/env/resource) that may have broken the pods.' },
1000
+ { name: 'get_source_file', effect: EToolEffect.READ, description: 'Fetches a file from a Git repo (GitHub/GitLab) at a ref — inspect the source behind a crash by following the stack trace to the offending file:line.' },
885
1001
  ];
886
1002
  // Resolves the tool names an agent may use: autoTools = full catalog, otherwise its own list
887
1003
  // (intersected with the catalog); readOnly filters out WRITE-effect tools. Pure (no LLM) → unit-testable.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kwirthmagnify/kwirth-common-ai",
3
- "version": "0.5.26",
3
+ "version": "0.5.28",
4
4
  "description": "Shared AI/LLM types and utilities for Kwirth AI plugins",
5
5
  "scripts": {
6
6
  "build": "del .\\dist\\* /s /q 2>nul & tsc",