@agentspec/sdk 0.2.3 → 0.2.4

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/index.cjs CHANGED
@@ -5,6 +5,7 @@ var zodToJsonSchema = require('zod-to-json-schema');
5
5
  var fs = require('fs');
6
6
  var path = require('path');
7
7
  var yaml = require('js-yaml');
8
+ var net = require('net');
8
9
 
9
10
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
10
11
 
@@ -300,7 +301,8 @@ var ComplianceSchema = zod.z.object({
300
301
  "memory-hygiene",
301
302
  "model-resilience",
302
303
  "evaluation-coverage",
303
- "observability"
304
+ "observability",
305
+ "metadata-quality"
304
306
  ])
305
307
  ).optional().describe('Compliance rule packs to evaluate during "agentspec audit". Each pack groups related rules. Omit to run all packs.'),
306
308
  suppressions: zod.z.array(ComplianceSuppressionSchema).optional().describe("Rules to suppress in audit output. Each suppression requires a reason and optional expiry date. Over-suppression is itself flagged."),
@@ -508,7 +510,7 @@ function loadManifest(filePath, opts = {}) {
508
510
  }
509
511
  let parsed;
510
512
  try {
511
- parsed = yaml__default.default.load(raw);
513
+ parsed = yaml__default.default.load(raw, { schema: yaml__default.default.JSON_SCHEMA });
512
514
  } catch (err) {
513
515
  throw new Error(`Invalid YAML in ${absPath}
514
516
  ${String(err)}`);
@@ -1072,8 +1074,6 @@ async function checkAws() {
1072
1074
  clearTimeout(timer);
1073
1075
  }
1074
1076
  }
1075
-
1076
- // src/health/checks/service.check.ts
1077
1077
  var TIMEOUT_MS = 3e3;
1078
1078
  async function runServiceChecks(services) {
1079
1079
  return Promise.all(services.map((svc) => checkService(svc)));
@@ -1149,11 +1149,25 @@ function parseConnectionUrl(connection) {
1149
1149
  }
1150
1150
  function classifyHost(host) {
1151
1151
  const h = host.replace(/^\[(.+)\]$/, "$1").toLowerCase();
1152
- if (h === "0.0.0.0") return "unspecified address 0.0.0.0 is not a valid service host";
1153
- if (h === "::1" || h === "localhost") return "loopback address is not probed from service checks";
1154
- if (h.startsWith("127.")) return "IPv4 loopback (127.x.x.x) is not probed from service checks";
1155
- if (h.startsWith("169.254.")) return "link-local address (169.254.x.x) blocked to prevent instance-metadata SSRF";
1156
- if (h.startsWith("fe80:")) return "IPv6 link-local (fe80::/10) blocked to prevent SSRF";
1152
+ if (h === "localhost") return "loopback address is not probed from service checks";
1153
+ const ipVersion = net.isIP(h);
1154
+ if (ipVersion === 4) {
1155
+ if (h === "0.0.0.0") return "unspecified address 0.0.0.0 is not a valid service host";
1156
+ if (h.startsWith("127.")) return "IPv4 loopback (127.x.x.x) is not probed from service checks";
1157
+ if (h.startsWith("169.254.")) return "link-local address (169.254.x.x) blocked to prevent instance-metadata SSRF";
1158
+ if (h.startsWith("10.")) return "RFC 1918 private address (10.0.0.0/8) blocked to prevent internal SSRF";
1159
+ if (h.startsWith("192.168.")) return "RFC 1918 private address (192.168.0.0/16) blocked to prevent internal SSRF";
1160
+ if (h.startsWith("172.")) {
1161
+ const second = parseInt(h.split(".")[1] ?? "0", 10);
1162
+ if (second >= 16 && second <= 31) {
1163
+ return "RFC 1918 private address (172.16.0.0/12) blocked to prevent internal SSRF";
1164
+ }
1165
+ }
1166
+ }
1167
+ if (ipVersion === 6) {
1168
+ if (h === "::1") return "loopback address is not probed from service checks";
1169
+ if (h.startsWith("fe80:")) return "IPv6 link-local (fe80::/10) blocked to prevent SSRF";
1170
+ }
1157
1171
  return null;
1158
1172
  }
1159
1173
  function getDefaultPort(scheme) {
@@ -1948,6 +1962,49 @@ var observabilityRules = [
1948
1962
  }
1949
1963
  ];
1950
1964
 
1965
+ // src/audit/rules/metadata.rules.ts
1966
+ var metadataRules = [
1967
+ {
1968
+ id: "META-01",
1969
+ pack: "metadata-quality",
1970
+ title: "Agent description declared",
1971
+ description: "Agents should have a non-empty description for fleet discovery and documentation",
1972
+ severity: "low",
1973
+ evidenceLevel: "declarative",
1974
+ check(manifest) {
1975
+ const desc = manifest.metadata.description;
1976
+ const pass = typeof desc === "string" && desc.trim().length > 0;
1977
+ return {
1978
+ pass,
1979
+ message: pass ? void 0 : "No description declared in metadata. Agents without descriptions are hard to discover in a fleet.",
1980
+ path: "/metadata/description",
1981
+ recommendation: "Add a concise metadata.description explaining what the agent does",
1982
+ references: []
1983
+ };
1984
+ }
1985
+ },
1986
+ {
1987
+ id: "META-02",
1988
+ pack: "metadata-quality",
1989
+ title: "Model temperature is production-safe",
1990
+ description: "Temperature above 1.5 causes unpredictable outputs that are unsuitable for production",
1991
+ severity: "medium",
1992
+ evidenceLevel: "declarative",
1993
+ check(manifest) {
1994
+ const temperature = manifest.spec.model.parameters?.temperature;
1995
+ if (temperature === void 0) return { pass: true };
1996
+ const pass = temperature <= 1.5;
1997
+ return {
1998
+ pass,
1999
+ message: pass ? void 0 : `Model temperature is ${temperature} \u2014 values above 1.5 produce unreliable outputs in production.`,
2000
+ path: "/spec/model/parameters/temperature",
2001
+ recommendation: "Set spec.model.parameters.temperature to 1.0 or lower for production agents",
2002
+ references: []
2003
+ };
2004
+ }
2005
+ }
2006
+ ];
2007
+
1951
2008
  // src/audit/index.ts
1952
2009
  var SEVERITY_WEIGHTS = {
1953
2010
  critical: 4,
@@ -1961,7 +2018,8 @@ var ALL_RULES = [
1961
2018
  ...securityRules,
1962
2019
  ...memoryRules,
1963
2020
  ...evaluationRules,
1964
- ...observabilityRules
2021
+ ...observabilityRules,
2022
+ ...metadataRules
1965
2023
  ];
1966
2024
  var AUDIT_RULE_IDS = new Set(ALL_RULES.map((r) => r.id));
1967
2025
  function isProofRecord(r) {
@@ -2125,6 +2183,62 @@ function generateAdapter(manifest, framework, options) {
2125
2183
  return adapter.generate(manifest, options);
2126
2184
  }
2127
2185
 
2186
+ // src/agent/usage-ledger.ts
2187
+ function createEmptyEntry(modelId) {
2188
+ return { modelId, promptTokens: 0, completionTokens: 0, totalTokens: 0, callCount: 0 };
2189
+ }
2190
+ function buildSnapshot(counters, windowStart) {
2191
+ const models = [...counters.values()].map((e) => ({ ...e }));
2192
+ let totalTokens = 0;
2193
+ let totalCalls = 0;
2194
+ for (const m of models) {
2195
+ totalTokens += m.totalTokens;
2196
+ totalCalls += m.callCount;
2197
+ }
2198
+ return {
2199
+ windowStartedAt: windowStart.toISOString(),
2200
+ models,
2201
+ totalTokens,
2202
+ totalCalls
2203
+ };
2204
+ }
2205
+ var UsageLedger = class {
2206
+ counters = /* @__PURE__ */ new Map();
2207
+ windowStart = /* @__PURE__ */ new Date();
2208
+ /**
2209
+ * Record token usage for a single LLM call.
2210
+ * Call this once per LLM invocation with the model ID and token counts.
2211
+ */
2212
+ record(modelId, promptTokens, completionTokens) {
2213
+ const p = Math.max(0, promptTokens);
2214
+ const c = Math.max(0, completionTokens);
2215
+ let entry = this.counters.get(modelId);
2216
+ if (!entry) {
2217
+ entry = createEmptyEntry(modelId);
2218
+ this.counters.set(modelId, entry);
2219
+ }
2220
+ entry.promptTokens += p;
2221
+ entry.completionTokens += c;
2222
+ entry.totalTokens += p + c;
2223
+ entry.callCount += 1;
2224
+ }
2225
+ /**
2226
+ * Return a frozen snapshot of the current usage window.
2227
+ *
2228
+ * @param reset - When true (default), clears all counters and starts a new
2229
+ * window. Use reset=true in the heartbeat push so each window is shipped
2230
+ * exactly once. Use reset=false for inspection without draining.
2231
+ */
2232
+ snapshot(reset = true) {
2233
+ const snap = buildSnapshot(this.counters, this.windowStart);
2234
+ if (reset) {
2235
+ this.counters = /* @__PURE__ */ new Map();
2236
+ this.windowStart = /* @__PURE__ */ new Date();
2237
+ }
2238
+ return snap;
2239
+ }
2240
+ };
2241
+
2128
2242
  // src/agent/reporter.ts
2129
2243
  var AgentSpecReporter = class {
2130
2244
  constructor(manifest, opts = {}) {
@@ -2141,6 +2255,8 @@ var AgentSpecReporter = class {
2141
2255
  refreshing = false;
2142
2256
  stopped = false;
2143
2257
  registeredTools = /* @__PURE__ */ new Set();
2258
+ /** In-process token usage accumulator. */
2259
+ usage = new UsageLedger();
2144
2260
  /**
2145
2261
  * Register a tool handler by name.
2146
2262
  * Only registered tools report status: 'pass' in the live health check.
@@ -2230,12 +2346,13 @@ var AgentSpecReporter = class {
2230
2346
  try {
2231
2347
  const health = await this.getReport();
2232
2348
  const gap = runAudit(this.manifest);
2349
+ const usage = this.usage.snapshot(false);
2233
2350
  const trimmedChecks = [...health.checks];
2234
- let body = JSON.stringify({ health, gap });
2351
+ let body = JSON.stringify({ health, gap, usage });
2235
2352
  if (body.length > 65536) {
2236
2353
  while (trimmedChecks.length > 0) {
2237
2354
  trimmedChecks.pop();
2238
- body = JSON.stringify({ health: { ...health, checks: trimmedChecks }, gap });
2355
+ body = JSON.stringify({ health: { ...health, checks: trimmedChecks }, gap, usage });
2239
2356
  if (body.length <= 65536) break;
2240
2357
  }
2241
2358
  }
@@ -2254,7 +2371,9 @@ var AgentSpecReporter = class {
2254
2371
  opts.onError?.(new Error(sanitized));
2255
2372
  return;
2256
2373
  }
2257
- if (!res.ok) {
2374
+ if (res.ok) {
2375
+ this.usage.snapshot(true);
2376
+ } else {
2258
2377
  opts.onError?.(new Error(`Heartbeat failed: HTTP ${res.status}`));
2259
2378
  }
2260
2379
  } catch (err) {
@@ -2345,6 +2464,14 @@ function agentSpecFastifyPlugin(reporter) {
2345
2464
  reply.status(500).send({ error: String(err) });
2346
2465
  }
2347
2466
  });
2467
+ app.get("/agentspec/usage", async (_req, reply) => {
2468
+ try {
2469
+ const snapshot = reporter.usage.snapshot(false);
2470
+ reply.status(200).send(snapshot);
2471
+ } catch (err) {
2472
+ reply.status(500).send({ error: String(err) });
2473
+ }
2474
+ });
2348
2475
  };
2349
2476
  }
2350
2477
 
@@ -2353,23 +2480,41 @@ function agentSpecExpressRouter(reporter) {
2353
2480
  const handler = async (req, res, next) => {
2354
2481
  const method = req.method?.toUpperCase() ?? "GET";
2355
2482
  const path = req.path ?? req.url ?? "";
2356
- if (method !== "GET" || path !== "/health") {
2483
+ if (method !== "GET") {
2357
2484
  next();
2358
2485
  return;
2359
2486
  }
2360
- try {
2361
- const report = await reporter.getReport();
2362
- res.status(200).json(report);
2363
- } catch (err) {
2487
+ if (path === "/health") {
2364
2488
  try {
2365
- res.status(500).json({ error: String(err) });
2366
- } catch {
2367
- next(err);
2489
+ const report = await reporter.getReport();
2490
+ res.status(200).json(report);
2491
+ } catch (err) {
2492
+ try {
2493
+ res.status(500).json({ error: String(err) });
2494
+ } catch {
2495
+ next(err);
2496
+ }
2368
2497
  }
2498
+ return;
2499
+ }
2500
+ if (path === "/usage") {
2501
+ try {
2502
+ const snapshot = reporter.usage.snapshot(false);
2503
+ res.status(200).json(snapshot);
2504
+ } catch (err) {
2505
+ try {
2506
+ res.status(500).json({ error: String(err) });
2507
+ } catch {
2508
+ next(err);
2509
+ }
2510
+ }
2511
+ return;
2369
2512
  }
2513
+ next();
2370
2514
  };
2371
2515
  handler._routes = [
2372
- { path: "/health" }
2516
+ { path: "/health" },
2517
+ { path: "/usage" }
2373
2518
  ];
2374
2519
  return handler;
2375
2520
  }
@@ -2378,6 +2523,7 @@ exports.AUDIT_RULE_IDS = AUDIT_RULE_IDS;
2378
2523
  exports.AgentSpecReporter = AgentSpecReporter;
2379
2524
  exports.LATEST_API_VERSION = LATEST_API_VERSION;
2380
2525
  exports.ManifestSchema = ManifestSchema;
2526
+ exports.UsageLedger = UsageLedger;
2381
2527
  exports.agentSpecExpressRouter = agentSpecExpressRouter;
2382
2528
  exports.agentSpecFastifyPlugin = agentSpecFastifyPlugin;
2383
2529
  exports.collectEnvRefs = collectEnvRefs;