@camstack/develop 0.1.39 → 0.1.40

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/CHANGELOG.md CHANGED
@@ -7,6 +7,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.1.40] - 2026-10-30
11
+
12
+ ### Changed
13
+
14
+ - Shared MCP helpers (query gate, two-step mutation gate, secret scrubbing, hub connection) now live here for the CLI and operator MCPs
15
+ - Shared read-only track-audit rules and hub wire schemas for the public MCP
16
+
10
17
  ## [0.1.39] - 2026-10-28
11
18
 
12
19
  ### Changed
package/dist/index.d.ts CHANGED
@@ -26,4 +26,13 @@ export { createHubAgent, explainTlsFailure, hubCaFileForServer, resolveHubTls, }
26
26
  export type { HubTlsConfig } from './hub/hub-tls.js';
27
27
  export { createHubClient, encodeTrpcInput, HubHttpError, HubRpcError, nodeHubTransport, } from './hub/hub-client.js';
28
28
  export type { HubClient, HubClientOptions, HubHttpMethod, HubTransport, HubTransportRequest, HubTransportResponse, } from './hub/hub-client.js';
29
+ export { scrubSecrets, scrubValue } from './mcp/scrub.js';
30
+ export { text, textError } from './mcp/text.js';
31
+ export { REDACTED, redactDeclaredSecrets, toToolOutput, truncateOutput, } from './mcp/redact.js';
32
+ export { CORE_QUERY_METHODS, loadApiIndex, parseApiIndex, type ApiIndex, type ApiMethod, type MethodAuth, type MethodKind, } from './mcp/api-index.js';
33
+ export { connectHub, tryConnectHub, type ConnectOutcome, type HubConnectOptions, type HubConnection, type NoSessionOutcome, } from './mcp/hub-connection.js';
34
+ export { gateQuery, isSecretBearing, type GateDecision, } from './mcp/query-gate.js';
35
+ export { CONFIRM_TTL_MS, MAX_OUTSTANDING_TOKENS, MUTATIONS_DISABLED_REASON, MutationGate, canonicalJson, digestArgs, runGated, stderrAudit, type AuditPhase, type AuditRecord, type AuditSink, type ConfirmDecision, type DryRunOutcome, type GatedResult, type GatedToolSpec, type IssuedToken, type MutationGateOptions, } from './mcp/mutation-gate.js';
36
+ export * from './mcp/ops/wire.js';
37
+ export * from './mcp/ops/track-findings.js';
29
38
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,kEAAkE;AAElE,YAAY,EACV,kBAAkB,EAClB,kBAAkB,EAClB,mBAAmB,EACnB,iBAAiB,EACjB,YAAY,EACZ,UAAU,EACV,kBAAkB,EAClB,iBAAiB,EACjB,oBAAoB,EACpB,mBAAmB,EACnB,kBAAkB,EAClB,iBAAiB,EACjB,SAAS,EACT,iBAAiB,EACjB,gBAAgB,EAChB,cAAc,GACf,MAAM,YAAY,CAAA;AAEnB,OAAO,EACL,iBAAiB,EACjB,oBAAoB,EACpB,qBAAqB,GACtB,MAAM,gBAAgB,CAAA;AAEvB,OAAO,EACL,WAAW,EACX,eAAe,EACf,WAAW,EACX,UAAU,GACX,MAAM,aAAa,CAAA;AAEpB,OAAO,EACL,gBAAgB,EAChB,iBAAiB,EACjB,WAAW,GACZ,MAAM,uBAAuB,CAAA;AAC9B,OAAO,EAAE,aAAa,EAAE,gBAAgB,EAAE,MAAM,6BAA6B,CAAA;AAE7E,OAAO,EAAE,aAAa,EAAE,MAAM,yBAAyB,CAAA;AACvD,OAAO,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAA;AAE9D,OAAO,EAAE,iBAAiB,EAAE,MAAM,uBAAuB,CAAA;AACzD,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAA;AAEnD,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAA;AACnD,OAAO,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAA;AACxD,OAAO,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAA;AAElD,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,gBAAgB,EAAE,MAAM,aAAa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AO,EAAE,YAAY,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAA;AACzD,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,MAAM,eAAe,CAAA;AAC/C,OAAO,EACL,QAAQ,EACR,qBAAqB,EACrB,YAAY,EACZ,cAAc,GACf,MAAM,iBAAiB,CAAA;AACxB,OAAO,EACL,kBAAkB,EAClB,YAAY,EACZ,aAAa,EACb,KAAK,QAAQ,EACb,KAAK,SAAS,EACd,KAAK,UAAU,EACf,KAAK,UAAU,GAChB,MAAM,oBAAoB,CAAA;AAC3B,OAAO,EACL,UAAU,EACV,aAAa,EACb,KAAK,cAAc,EACnB,KAAK,iBAAiB,EACtB,KAAK,aAAa,EAClB,KAAK,gBAAgB,GACtB,MAAM,yBAAyB,CAAA;AAChC,OAAO,EACL,SAAS,EACT,eAAe,EACf,KAAK,YAAY,GAClB,MAAM,qBAAqB,CAAA;AAC5B,OAAO,EACL,cAAc,EACd,sBAAsB,EACtB,yBAAyB,EACzB,YAAY,EACZ,aAAa,EACb,UAAU,EACV,QAAQ,EACR,WAAW,EACX,KAAK,UAAU,EACf,KAAK,WAAW,EAChB,KAAK,SAAS,EACd,KAAK,eAAe,EACpB,KAAK,aAAa,EAClB,KAAK,WAAW,EAChB,KAAK,aAAa,EAClB,KAAK,WAAW,EAChB,KAAK,mBAAmB,GACzB,MAAM,wBAAwB,CAAA;AAG/B,cAAc,mBAAmB,CAAA;AACjC,cAAc,6BAA6B,CAAA"}
package/dist/index.js CHANGED
@@ -21,3 +21,17 @@ export { DEFAULT_HUB_PORT, HubAddressError, normalizeHubAddress, validateHubAddr
21
21
  export { resolveHubUrl } from './hub/hub-url.js';
22
22
  export { createHubAgent, explainTlsFailure, hubCaFileForServer, resolveHubTls, } from './hub/hub-tls.js';
23
23
  export { createHubClient, encodeTrpcInput, HubHttpError, HubRpcError, nodeHubTransport, } from './hub/hub-client.js';
24
+ // MCP shared helpers: the query gate, the mutation gate (D836), the secret
25
+ // scrubbers and the output redaction, shared by `camstack mcp` and the private
26
+ // operator MCP.
27
+ export { scrubSecrets, scrubValue } from './mcp/scrub.js';
28
+ export { text, textError } from './mcp/text.js';
29
+ export { REDACTED, redactDeclaredSecrets, toToolOutput, truncateOutput, } from './mcp/redact.js';
30
+ export { CORE_QUERY_METHODS, loadApiIndex, parseApiIndex, } from './mcp/api-index.js';
31
+ export { connectHub, tryConnectHub, } from './mcp/hub-connection.js';
32
+ export { gateQuery, isSecretBearing, } from './mcp/query-gate.js';
33
+ export { CONFIRM_TTL_MS, MAX_OUTSTANDING_TOKENS, MUTATIONS_DISABLED_REASON, MutationGate, canonicalJson, digestArgs, runGated, stderrAudit, } from './mcp/mutation-gate.js';
34
+ // Hub payload slices and the per-track audit rules, shared by `camstack mcp`
35
+ // (ops toolset) and the private operator MCP.
36
+ export * from './mcp/ops/wire.js';
37
+ export * from './mcp/ops/track-findings.js';
@@ -0,0 +1,18 @@
1
+ export type MethodKind = 'query' | 'mutation' | 'subscription';
2
+ export type MethodAuth = 'public' | 'protected' | 'admin';
3
+ export interface ApiMethod {
4
+ readonly path: string;
5
+ readonly kind: MethodKind;
6
+ readonly auth: MethodAuth;
7
+ readonly capability: string;
8
+ }
9
+ export type ApiIndex = ReadonlyMap<string, ApiMethod>;
10
+ /** Parse the method-index table out of the generated api.md text. */
11
+ export declare function parseApiIndex(markdown: string): ApiIndex;
12
+ /**
13
+ * Fixed core routers that are not capabilities (so not in the generated table):
14
+ * the in-RAM log ring and the capability registry's read side. All admin-tier.
15
+ */
16
+ export declare const CORE_QUERY_METHODS: readonly ApiMethod[];
17
+ export declare function loadApiIndex(workspaceRoot: string): ApiIndex;
18
+ //# sourceMappingURL=api-index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"api-index.d.ts","sourceRoot":"","sources":["../../src/mcp/api-index.ts"],"names":[],"mappings":"AAWA,MAAM,MAAM,UAAU,GAAG,OAAO,GAAG,UAAU,GAAG,cAAc,CAAA;AAC9D,MAAM,MAAM,UAAU,GAAG,QAAQ,GAAG,WAAW,GAAG,OAAO,CAAA;AAEzD,MAAM,WAAW,SAAS;IACxB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA;IACrB,QAAQ,CAAC,IAAI,EAAE,UAAU,CAAA;IACzB,QAAQ,CAAC,IAAI,EAAE,UAAU,CAAA;IACzB,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAA;CAC5B;AAED,MAAM,MAAM,QAAQ,GAAG,WAAW,CAAC,MAAM,EAAE,SAAS,CAAC,CAAA;AAYrD,qEAAqE;AACrE,wBAAgB,aAAa,CAAC,QAAQ,EAAE,MAAM,GAAG,QAAQ,CAYxD;AAED;;;GAGG;AACH,eAAO,MAAM,kBAAkB,EAAE,SAAS,SAAS,EAUlD,CAAA;AAED,wBAAgB,YAAY,CAAC,aAAa,EAAE,MAAM,GAAG,QAAQ,CAc5D"}
@@ -0,0 +1,64 @@
1
+ /**
2
+ * The hub's method catalogue as the repository generates it
3
+ * (`docs/reference/api.md`, "Method index": tRPC path | kind | auth | capability).
4
+ *
5
+ * `hub_query` trusts this table and nothing else for "is it a query?" and "what
6
+ * tier does it need?" — a method the generator did not emit is refused, which is
7
+ * also how a hallucinated path is caught before it reaches the hub.
8
+ */
9
+ import * as fs from 'node:fs';
10
+ import * as path from 'node:path';
11
+ const ROW = /^\|\s*`([A-Za-z0-9_.]+)`\s*\|\s*(\w+)\s*\|\s*(\w+)\s*\|\s*([^|]+?)\s*\|\s*$/;
12
+ function isKind(value) {
13
+ return value === 'query' || value === 'mutation' || value === 'subscription';
14
+ }
15
+ function isAuth(value) {
16
+ return value === 'public' || value === 'protected' || value === 'admin';
17
+ }
18
+ /** Parse the method-index table out of the generated api.md text. */
19
+ export function parseApiIndex(markdown) {
20
+ const out = new Map();
21
+ for (const line of markdown.split('\n')) {
22
+ const m = ROW.exec(line);
23
+ if (!m)
24
+ continue;
25
+ const [, methodPath, kind, auth, capability] = m;
26
+ if (!methodPath || !kind || !auth || !capability)
27
+ continue;
28
+ if (!isKind(kind) || !isAuth(auth))
29
+ continue;
30
+ if (out.has(methodPath))
31
+ continue;
32
+ out.set(methodPath, { path: methodPath, kind, auth, capability });
33
+ }
34
+ return out;
35
+ }
36
+ /**
37
+ * Fixed core routers that are not capabilities (so not in the generated table):
38
+ * the in-RAM log ring and the capability registry's read side. All admin-tier.
39
+ */
40
+ export const CORE_QUERY_METHODS = [
41
+ { path: 'logs.query', kind: 'query', auth: 'admin', capability: '(core) logs' },
42
+ { path: 'capabilities.listCapabilities', kind: 'query', auth: 'admin', capability: '(core)' },
43
+ { path: 'capabilities.getCapability', kind: 'query', auth: 'admin', capability: '(core)' },
44
+ {
45
+ path: 'capabilities.getDeviceCapabilities',
46
+ kind: 'query',
47
+ auth: 'admin',
48
+ capability: '(core)',
49
+ },
50
+ ];
51
+ export function loadApiIndex(workspaceRoot) {
52
+ const file = path.join(workspaceRoot, 'docs', 'reference', 'api.md');
53
+ let text;
54
+ try {
55
+ text = fs.readFileSync(file, 'utf8');
56
+ }
57
+ catch (err) {
58
+ throw new Error(`cannot read ${file} — run \`npm run docs:generate\` in the CamStack checkout (the ops tools take the method catalogue from it)`, { cause: err });
59
+ }
60
+ const index = new Map(parseApiIndex(text));
61
+ for (const core of CORE_QUERY_METHODS)
62
+ index.set(core.path, core);
63
+ return index;
64
+ }
@@ -0,0 +1,46 @@
1
+ import { type CredentialSource, type CredentialTier } from '../hub/credentials.js';
2
+ import { type HubClient, type HubTransport } from '../hub/hub-client.js';
3
+ import { type HubTlsConfig } from '../hub/hub-tls.js';
4
+ export interface HubConnectOptions {
5
+ /** A checkout whose `scratchpad/.hub-url` may name the hub (the CLI passes its cwd). */
6
+ readonly workspaceRoot: string;
7
+ /** `--token-file` of the MCP entry. */
8
+ readonly tokenFile?: string;
9
+ /** `--server` of the MCP entry. */
10
+ readonly server?: string;
11
+ readonly env?: Readonly<Record<string, string | undefined>>;
12
+ /** The session cache directory (tests); defaults to `~/.camstack`. */
13
+ readonly sessionDir?: string;
14
+ readonly transport?: HubTransport;
15
+ /** The exact `camstack login` command to show (tests); default: derived from PATH. */
16
+ readonly loginCommand?: string;
17
+ }
18
+ export interface HubConnection {
19
+ readonly server: string;
20
+ readonly token: string;
21
+ readonly tier: CredentialTier;
22
+ readonly source: CredentialSource;
23
+ readonly tls: HubTlsConfig;
24
+ readonly client: HubClient;
25
+ readonly adminHint: string | null;
26
+ readonly loginCommand: string;
27
+ }
28
+ export declare function connectHub(options: HubConnectOptions): Promise<HubConnection>;
29
+ /** A tool that needs a hub and finds no usable session: a result, never a throw. */
30
+ export interface NoSessionOutcome {
31
+ readonly ok: false;
32
+ readonly reason: 'no-session';
33
+ readonly message: string;
34
+ readonly action: string;
35
+ }
36
+ export type ConnectOutcome = {
37
+ readonly ok: true;
38
+ readonly connection: HubConnection;
39
+ } | NoSessionOutcome;
40
+ /**
41
+ * {@link connectHub}, with "no hub address" and "no credentials" turned into a
42
+ * structured outcome that names the one command to run. Other failures (a TLS
43
+ * problem, a refused refresh) still throw: they are not a missing login.
44
+ */
45
+ export declare function tryConnectHub(options: HubConnectOptions): Promise<ConnectOutcome>;
46
+ //# sourceMappingURL=hub-connection.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hub-connection.d.ts","sourceRoot":"","sources":["../../src/mcp/hub-connection.ts"],"names":[],"mappings":"AASA,OAAO,EAEL,KAAK,gBAAgB,EACrB,KAAK,cAAc,EACpB,MAAM,uBAAuB,CAAA;AAC9B,OAAO,EAAmB,KAAK,SAAS,EAAE,KAAK,YAAY,EAAE,MAAM,sBAAsB,CAAA;AAGzF,OAAO,EAAiB,KAAK,YAAY,EAAE,MAAM,mBAAmB,CAAA;AAGpE,MAAM,WAAW,iBAAiB;IAChC,wFAAwF;IACxF,QAAQ,CAAC,aAAa,EAAE,MAAM,CAAA;IAC9B,uCAAuC;IACvC,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,CAAA;IAC3B,mCAAmC;IACnC,QAAQ,CAAC,MAAM,CA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OAAO,CAAC,cAAc,CAAC,CAiBvF"}
@@ -0,0 +1,100 @@
1
+ /**
2
+ * How an MCP server reaches a hub: the CLI's own credential chain, nothing
3
+ * else (D835). `--token-file`, then the `camstack login` session, renewed
4
+ * automatically. No `$CAMSTACK_TOKEN`: a secret does not travel through the
5
+ * environment. TLS is pinned or the system store, never switched off.
6
+ *
7
+ * Shared by `camstack mcp` and the private operator MCP so there is one chain.
8
+ */
9
+ import { adminCredentialHint, sessionLoginCommand } from '../hub/login-hints.js';
10
+ import { MissingCredentialsError, } from '../hub/credentials.js';
11
+ import { createHubClient } from '../hub/hub-client.js';
12
+ import { refreshOnUnauthorized, resolveFreshCredentials } from '../hub/session-refresh.js';
13
+ import { loadSession } from '../hub/session-store.js';
14
+ import { resolveHubTls } from '../hub/hub-tls.js';
15
+ import { resolveHubUrl } from '../hub/hub-url.js';
16
+ /** The environment keys the MCP honours: addresses and PATHS, never a secret. */
17
+ const HONOURED_ENV = ['CAMSTACK_HUB_URL', 'CAMSTACK_SERVER', 'CAMSTACK_HUB_CA_FILE'];
18
+ function honouredEnv(env) {
19
+ const out = {};
20
+ for (const key of HONOURED_ENV)
21
+ out[key] = env[key];
22
+ return out;
23
+ }
24
+ export async function connectHub(options) {
25
+ const env = honouredEnv(options.env ?? process.env);
26
+ const dir = options.sessionDir;
27
+ const session = loadSession(undefined, dir);
28
+ const hub = resolveHubUrl({
29
+ ...(options.server ? { explicit: options.server } : {}),
30
+ env,
31
+ workspaceRoot: options.workspaceRoot,
32
+ session,
33
+ });
34
+ if (!hub) {
35
+ throw new Error('no hub address: pass --server, set CAMSTACK_HUB_URL, write <checkout>/scratchpad/.hub-url, or run `camstack login`');
36
+ }
37
+ const loginCommand = options.loginCommand ?? sessionLoginCommand();
38
+ const tls = resolveHubTls(hub.url, env, dir);
39
+ const credentials = await resolveFreshCredentials({
40
+ server: hub.url,
41
+ ...(options.tokenFile ? { tokenFile: options.tokenFile } : {}),
42
+ env: { CAMSTACK_SERVER: hub.url },
43
+ loadSession: (server) => loadSession(server, dir),
44
+ ...(dir ? { dir } : {}),
45
+ tls,
46
+ ...(options.transport ? { transport: options.transport } : {}),
47
+ });
48
+ const client = createHubClient({
49
+ baseUrl: hub.url,
50
+ token: credentials.token,
51
+ tls,
52
+ ...(options.transport ? { transport: options.transport } : {}),
53
+ // A 401 on a login session renews it once and retries once.
54
+ ...(credentials.source === 'session'
55
+ ? {
56
+ onUnauthorized: refreshOnUnauthorized({
57
+ server: hub.url,
58
+ ...(dir ? { dir } : {}),
59
+ tls,
60
+ ...(options.transport ? { transport: options.transport } : {}),
61
+ }),
62
+ }
63
+ : {}),
64
+ });
65
+ const adminHint = credentials.tier === 'admin' ? null : adminCredentialHint(loginCommand);
66
+ return {
67
+ server: hub.url,
68
+ token: credentials.token,
69
+ tier: credentials.tier,
70
+ source: credentials.source,
71
+ tls,
72
+ client,
73
+ adminHint,
74
+ loginCommand,
75
+ };
76
+ }
77
+ /**
78
+ * {@link connectHub}, with "no hub address" and "no credentials" turned into a
79
+ * structured outcome that names the one command to run. Other failures (a TLS
80
+ * problem, a refused refresh) still throw: they are not a missing login.
81
+ */
82
+ export async function tryConnectHub(options) {
83
+ const loginCommand = options.loginCommand ?? sessionLoginCommand();
84
+ const action = `run \`${loginCommand} <host>\` in a terminal`;
85
+ try {
86
+ return { ok: true, connection: await connectHub(options) };
87
+ }
88
+ catch (err) {
89
+ const message = err instanceof Error ? err.message : String(err);
90
+ if (err instanceof MissingCredentialsError || message.startsWith('no hub address')) {
91
+ return {
92
+ ok: false,
93
+ reason: 'no-session',
94
+ message: `no usable hub session: ${message}`,
95
+ action,
96
+ };
97
+ }
98
+ throw err;
99
+ }
100
+ }
@@ -0,0 +1,87 @@
1
+ /** How long a dry run stays confirmable. Short on purpose: the world moves. */
2
+ export declare const CONFIRM_TTL_MS: number;
3
+ /** Outstanding dry runs kept at once; the oldest is dropped beyond this. */
4
+ export declare const MAX_OUTSTANDING_TOKENS = 16;
5
+ export type AuditPhase = 'dry-run' | 'execute' | 'refused' | 'failed' | 'executed';
6
+ export interface AuditRecord {
7
+ readonly at: string;
8
+ readonly tool: string;
9
+ readonly phase: AuditPhase;
10
+ readonly argsDigest: string;
11
+ readonly detail: string;
12
+ readonly args?: unknown;
13
+ }
14
+ export type AuditSink = (record: AuditRecord) => void;
15
+ /** Default sink: one JSON line on stderr (stdout belongs to the MCP wire). */
16
+ export declare const stderrAudit: AuditSink;
17
+ /** Key-sorted JSON, so two spellings of the same arguments digest alike. */
18
+ export declare function canonicalJson(value: unknown): string;
19
+ export declare function digestArgs(tool: string, args: unknown): string;
20
+ export type ConfirmDecision = {
21
+ readonly ok: true;
22
+ } | {
23
+ readonly ok: false;
24
+ readonly reason: string;
25
+ };
26
+ export interface MutationGateOptions {
27
+ /** `--allow-mutations`. */
28
+ readonly allowMutations: boolean;
29
+ readonly audit?: AuditSink;
30
+ readonly now?: () => number;
31
+ /** Injectable for tests; defaults to 128 random bits. */
32
+ readonly newToken?: () => string;
33
+ readonly ttlMs?: number;
34
+ }
35
+ export interface IssuedToken {
36
+ readonly confirmToken: string;
37
+ readonly expiresAt: number;
38
+ }
39
+ export declare const MUTATIONS_DISABLED_REASON = "mutations are disabled: start the server with --allow-mutations (the camstack-ops entry in .mcp.json does not set it by default)";
40
+ export declare class MutationGate {
41
+ private readonly options;
42
+ private readonly outstanding;
43
+ private readonly audit;
44
+ private readonly now;
45
+ private readonly newToken;
46
+ private readonly ttlMs;
47
+ constructor(options: MutationGateOptions);
48
+ get enabled(): boolean;
49
+ record(tool: string, phase: AuditPhase, args: unknown, detail: string): void;
50
+ /** Issue the token of a dry run. Throws when mutations are disabled. */
51
+ issue(tool: string, args: unknown): IssuedToken;
52
+ /** Check and CONSUME a presented token. */
53
+ confirm(tool: string, args: unknown, token: string): ConfirmDecision;
54
+ private sweep;
55
+ }
56
+ export interface DryRunOutcome {
57
+ /** What would happen. Shown to the operator. */
58
+ readonly describe: unknown;
59
+ /** False when there is nothing to confirm (the preflight refused). */
60
+ readonly confirmable: boolean;
61
+ }
62
+ export interface GatedToolSpec<A> {
63
+ readonly tool: string;
64
+ /** Read-only. Must never call the mutating method. */
65
+ readonly dryRun: (args: A) => Promise<DryRunOutcome>;
66
+ /** The one place the mutation happens. */
67
+ readonly execute: (args: A) => Promise<unknown>;
68
+ }
69
+ export type GatedResult = {
70
+ readonly status: 'refused';
71
+ readonly reason: string;
72
+ } | {
73
+ readonly status: 'dry-run';
74
+ readonly confirm_token?: string;
75
+ readonly expiresAt?: string;
76
+ readonly dryRun: unknown;
77
+ readonly next: string;
78
+ } | {
79
+ readonly status: 'executed';
80
+ readonly result: unknown;
81
+ };
82
+ /**
83
+ * Drive one gated call: dry run without a token, execute with a valid one.
84
+ * `args` excludes `confirm_token`; the token is passed beside it.
85
+ */
86
+ export declare function runGated<A>(gate: MutationGate, spec: GatedToolSpec<A>, args: A, confirmToken: string | undefined): Promise<GatedResult>;
87
+ //# sourceMappingURL=mutation-gate.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mutation-gate.d.ts","sourceRoot":"","sources":["../../src/mcp/mutation-gate.ts"],"names":[],"mappings":"AAmBA,+EAA+E;AAC/E,eAAO,MAAM,cAAc,EAAE,MAAmB,CAAA;AAChD,4EAA4E;AAC5E,eAAO,MAAM,sBAAsB,KAAK,CAAA;AAExC,MAAM,MAAM,UAAU,GAAG,SAAS,GAAG,SAAS,GAAG,SAAS,GAAG,QAAQ,GAAG,UAAU,CAAA;AAElF,MAAM,WAAW,WAAW;IAC1B,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAA;IACnB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA;IACrB,QAAQ,CAAC,KAAK,EAAE,UAAU,CAAA;IAC1B,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAA;IAC3B,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAA;IACvB,QAAQ,CAAC,IAAI,CAAC,EAAE,OAAO,CAAA;CACxB;AAED,MAAM,MAAM,SAAS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,MAAM,EAAE,UAAU,CAAC;IAAC,QAAQ,CAAC,MAAM,EAAE,OAAO,CAAA;CAAE,CAAA;AAE7D;;;GAGG;AACH,wBAAsB,QAAQ,CAAC,CAAC,EAC9B,IAAI,EAAE,YAAY,EAClB,IAAI,EAAE,aAAa,CAAC,CAAC,CAAC,EACtB,IAAI,EAAE,CAAC,EACP,YAAY,EAAE,MAAM,GAAG,SAAS,GAC/B,OAAO,CAAC,WAAW,CAAC,CAyCtB"}
@@ -0,0 +1,171 @@
1
+ /**
2
+ * The mutation gate (plan §3.7, §3.10; D836).
3
+ *
4
+ * A mutating tool never acts on its first call. The first call (no
5
+ * `confirm_token`) is a DRY RUN: it describes what would happen and returns a
6
+ * one-shot token BOUND to the tool and to the exact arguments. Only a second
7
+ * call carrying that token executes, and only if
8
+ *
9
+ * - the server was started with `--allow-mutations`,
10
+ * - the token exists, has not expired, and was issued for this tool,
11
+ * - the arguments are byte-for-byte the ones the dry run described.
12
+ *
13
+ * A token is consumed the moment it is presented, success or not: a mismatch,
14
+ * an expiry or a failed execution all require a fresh dry run. Every call —
15
+ * refused ones included — is written to the audit sink.
16
+ */
17
+ import { createHash, randomBytes } from 'node:crypto';
18
+ import { scrubValue } from './scrub.js';
19
+ /** How long a dry run stays confirmable. Short on purpose: the world moves. */
20
+ export const CONFIRM_TTL_MS = 5 * 60_000;
21
+ /** Outstanding dry runs kept at once; the oldest is dropped beyond this. */
22
+ export const MAX_OUTSTANDING_TOKENS = 16;
23
+ /** Default sink: one JSON line on stderr (stdout belongs to the MCP wire). */
24
+ export const stderrAudit = (record) => {
25
+ process.stderr.write(`[camstack-ops:audit] ${JSON.stringify(scrubValue(record))}\n`);
26
+ };
27
+ /** Key-sorted JSON, so two spellings of the same arguments digest alike. */
28
+ export function canonicalJson(value) {
29
+ if (Array.isArray(value))
30
+ return `[${value.map((v) => canonicalJson(v)).join(',')}]`;
31
+ if (value !== null && typeof value === 'object') {
32
+ const entries = Object.entries(value)
33
+ .filter(([, v]) => v !== undefined)
34
+ .toSorted(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
35
+ return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${canonicalJson(v)}`).join(',')}}`;
36
+ }
37
+ return JSON.stringify(value) ?? 'null';
38
+ }
39
+ export function digestArgs(tool, args) {
40
+ return createHash('sha256')
41
+ .update(`${tool}\n${canonicalJson(args)}`)
42
+ .digest('hex');
43
+ }
44
+ export const MUTATIONS_DISABLED_REASON = 'mutations are disabled: start the server with --allow-mutations (the camstack-ops entry in .mcp.json does not set it by default)';
45
+ export class MutationGate {
46
+ options;
47
+ outstanding = new Map();
48
+ audit;
49
+ now;
50
+ newToken;
51
+ ttlMs;
52
+ constructor(options) {
53
+ this.options = options;
54
+ this.audit = options.audit ?? stderrAudit;
55
+ this.now = options.now ?? Date.now;
56
+ this.newToken = options.newToken ?? (() => `cfm_${randomBytes(16).toString('hex')}`);
57
+ this.ttlMs = options.ttlMs ?? CONFIRM_TTL_MS;
58
+ }
59
+ get enabled() {
60
+ return this.options.allowMutations;
61
+ }
62
+ record(tool, phase, args, detail) {
63
+ this.audit({
64
+ at: new Date(this.now()).toISOString(),
65
+ tool,
66
+ phase,
67
+ argsDigest: digestArgs(tool, args),
68
+ detail,
69
+ args,
70
+ });
71
+ }
72
+ /** Issue the token of a dry run. Throws when mutations are disabled. */
73
+ issue(tool, args) {
74
+ if (!this.enabled)
75
+ throw new Error(MUTATIONS_DISABLED_REASON);
76
+ this.sweep();
77
+ while (this.outstanding.size >= MAX_OUTSTANDING_TOKENS) {
78
+ const oldest = this.outstanding.keys().next();
79
+ if (oldest.done)
80
+ break;
81
+ this.outstanding.delete(oldest.value);
82
+ }
83
+ const confirmToken = this.newToken();
84
+ const expiresAt = this.now() + this.ttlMs;
85
+ this.outstanding.set(confirmToken, { tool, digest: digestArgs(tool, args), expiresAt });
86
+ return { confirmToken, expiresAt };
87
+ }
88
+ /** Check and CONSUME a presented token. */
89
+ confirm(tool, args, token) {
90
+ if (!this.enabled)
91
+ return { ok: false, reason: MUTATIONS_DISABLED_REASON };
92
+ const found = this.outstanding.get(token);
93
+ this.outstanding.delete(token);
94
+ if (!found) {
95
+ return {
96
+ ok: false,
97
+ reason: 'confirm_token is unknown, already used, or from another session — call the tool again without it for a fresh dry run',
98
+ };
99
+ }
100
+ if (found.expiresAt <= this.now()) {
101
+ return {
102
+ ok: false,
103
+ reason: 'confirm_token expired — call the tool again for a fresh dry run',
104
+ };
105
+ }
106
+ if (found.tool !== tool) {
107
+ return { ok: false, reason: `confirm_token was issued for ${found.tool}, not ${tool}` };
108
+ }
109
+ if (found.digest !== digestArgs(tool, args)) {
110
+ return {
111
+ ok: false,
112
+ reason: 'the arguments differ from the dry run this confirm_token was issued for — token burned; call the tool again for a fresh dry run',
113
+ };
114
+ }
115
+ return { ok: true };
116
+ }
117
+ sweep() {
118
+ const t = this.now();
119
+ for (const [token, entry] of this.outstanding) {
120
+ if (entry.expiresAt <= t)
121
+ this.outstanding.delete(token);
122
+ }
123
+ }
124
+ }
125
+ /**
126
+ * Drive one gated call: dry run without a token, execute with a valid one.
127
+ * `args` excludes `confirm_token`; the token is passed beside it.
128
+ */
129
+ export async function runGated(gate, spec, args, confirmToken) {
130
+ const { tool } = spec;
131
+ if (!gate.enabled) {
132
+ gate.record(tool, 'refused', args, 'mutations disabled');
133
+ return { status: 'refused', reason: MUTATIONS_DISABLED_REASON };
134
+ }
135
+ if (confirmToken === undefined) {
136
+ const outcome = await spec.dryRun(args);
137
+ if (!outcome.confirmable) {
138
+ gate.record(tool, 'dry-run', args, 'not confirmable (preflight refused)');
139
+ return {
140
+ status: 'dry-run',
141
+ dryRun: outcome.describe,
142
+ next: 'Nothing to confirm: the preflight refused this plan. Fix what it names and dry-run again.',
143
+ };
144
+ }
145
+ const issued = gate.issue(tool, args);
146
+ gate.record(tool, 'dry-run', args, 'token issued');
147
+ return {
148
+ status: 'dry-run',
149
+ confirm_token: issued.confirmToken,
150
+ expiresAt: new Date(issued.expiresAt).toISOString(),
151
+ dryRun: outcome.describe,
152
+ next: `Nothing was changed. To execute, call ${tool} again with the SAME arguments and confirm_token. The token is single-use and expires.`,
153
+ };
154
+ }
155
+ const decision = gate.confirm(tool, args, confirmToken);
156
+ if (!decision.ok) {
157
+ gate.record(tool, 'refused', args, decision.reason);
158
+ return { status: 'refused', reason: decision.reason };
159
+ }
160
+ gate.record(tool, 'execute', args, 'confirmed — executing');
161
+ try {
162
+ const result = await spec.execute(args);
163
+ gate.record(tool, 'executed', args, 'ok');
164
+ return { status: 'executed', result };
165
+ }
166
+ catch (err) {
167
+ const message = err instanceof Error ? err.message : String(err);
168
+ gate.record(tool, 'failed', args, message);
169
+ throw err;
170
+ }
171
+ }
@@ -0,0 +1,67 @@
1
+ /**
2
+ * Per-track audit rules — pure, shared by the operator MCP and `camstack mcp`.
3
+ *
4
+ * Aggregate percentages of missing media MISS the defects an operator sees;
5
+ * this inspects EVERY track (trajectory, media rows, timing, enrichment) and
6
+ * emits per-track findings. Thresholds were tuned on the 2026-07-22 triage.
7
+ * The detection rules are pure ({@link analyzeTrack}); the fetch loop around
8
+ * them lives with each caller.
9
+ *
10
+ * Reading a finding, and the hard rule to LOOK at a flagged track's media before
11
+ * claiming a fix: `.claude/skills/audit-debug-tracks/SKILL.md`.
12
+ */
13
+ import type { MediaInfo, Track } from './wire.js';
14
+ export declare const FINDING_CODES: readonly ["ZERO_MEDIA", "MISSING_FIRSTFRAME", "MISSING_LASTFRAME", "MISSING_THUMBNAIL", "FF_EQ_LF", "LASTFRAME_STALE", "MEDIA_STOPPED_EARLY", "BEST_SHOT_STALE", "BEST_AT_EDGE", "ENDED_MID_FRAME", "FRAGMENT_SUSPECT", "FACE_EXPECTED_MISSING", "PLATE_EXPECTED_MISSING", "MEDIA_UNREADABLE", "DEVICE_AUDIT_ERROR"];
15
+ export type FindingCode = (typeof FINDING_CODES)[number];
16
+ export interface Finding {
17
+ readonly deviceId: number;
18
+ readonly trackId: string;
19
+ readonly className: string;
20
+ readonly code: FindingCode;
21
+ readonly detail: string;
22
+ }
23
+ export declare const THRESHOLDS: {
24
+ readonly lastFrameStaleMs: 2000;
25
+ readonly mediaCoverageMin: 0.5;
26
+ readonly longTrackMs: 5000;
27
+ readonly betterShotRatio: 1.5;
28
+ readonly edgeFraction: 0.01;
29
+ readonly faceMinTrackMs: 3000;
30
+ readonly plateMinTrackMs: 2000;
31
+ readonly fragmentMaxMs: 1500;
32
+ readonly fragmentNeighborWindowMs: 15000;
33
+ };
34
+ interface Box {
35
+ readonly x: number;
36
+ readonly y: number;
37
+ readonly w: number;
38
+ readonly h: number;
39
+ }
40
+ export declare const isSynthetic: (t: Track) => boolean;
41
+ /** Detection-grid dimensions, estimated from positions and the normalised envelope. */
42
+ export declare function frameDims(track: Track): {
43
+ readonly W: number;
44
+ readonly H: number;
45
+ };
46
+ export declare function touchesEdge(b: Box, W: number, H: number): boolean;
47
+ export interface EnrichmentProbe {
48
+ /** `null`: not checked (the track did not qualify). */
49
+ readonly face: 'held' | 'missing' | null;
50
+ readonly plate: 'held' | 'missing' | null;
51
+ }
52
+ export interface AnalyzeInput {
53
+ readonly track: Track;
54
+ /** The other tracks of the same camera and window, for fragment detection. */
55
+ readonly siblings: readonly Track[];
56
+ /** `null` = media could not be read (every media finding is then UNKNOWN). */
57
+ readonly media: readonly MediaInfo[] | null;
58
+ /** firstFrame/lastFrame byte-identical; `null` = not determined. */
59
+ readonly ffEqualsLf: boolean | null;
60
+ readonly enrichment: EnrichmentProbe;
61
+ }
62
+ /** The audit rules for one track. Pure: same input, same findings. */
63
+ export declare function analyzeTrack(input: AnalyzeInput): Finding[];
64
+ export declare function qualifiesForFace(track: Track, faceDevices: ReadonlySet<number>): boolean;
65
+ export declare function qualifiesForPlate(track: Track, plateDevices: ReadonlySet<number>): boolean;
66
+ export {};
67
+ //# sourceMappingURL=track-findings.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"track-findings.d.ts","sourceRoot":"","sources":["../../../src/mcp/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;CAC1C;AAED,MAAM,WAAW,YAAY;IAC3B,QAAQ,CAAC,KAAK,EAAE,KAAK,CAAA;IACrB,8EAA8E;IAC9E,QAAQ,CAAC,QAAQ,EAAE,SAAS,KAAK,EAAE,CAAA;IACnC,8EAA8E;IAC9E,QAAQ,CAAC,KAAK,EAAE,SAAS,SAAS,EAAE,GAAG,IAAI,CAAA;IAC3C,oEAAoE;IACpE,QAAQ,CAAC,UAAU,EAAE,OAAO,GAAG,IAAI,CAAA;IACnC,QAAQ,CAAC,UAAU,EAAE,eAAe,CAAA;CACrC;AAiBD,sEAAsE;AACtE,wBAAgB,YAAY,CAAC,KAAK,EAAE,YAAY,GAAG,OAAO,EAAE,CA2G3D;AAED,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,KAAK,EAAE,WAAW,EAAE,WAAW,CAAC,MAAM,CAAC,GAAG,OAAO,CAMxF;AAED,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,KAAK,EAAE,YAAY,EAAE,WAAW,CAAC,MAAM,CAAC,GAAG,OAAO,CAM1F"}
@@ -0,0 +1,163 @@
1
+ export const FINDING_CODES = [
2
+ 'ZERO_MEDIA',
3
+ 'MISSING_FIRSTFRAME',
4
+ 'MISSING_LASTFRAME',
5
+ 'MISSING_THUMBNAIL',
6
+ 'FF_EQ_LF',
7
+ 'LASTFRAME_STALE',
8
+ 'MEDIA_STOPPED_EARLY',
9
+ 'BEST_SHOT_STALE',
10
+ 'BEST_AT_EDGE',
11
+ 'ENDED_MID_FRAME',
12
+ 'FRAGMENT_SUSPECT',
13
+ 'FACE_EXPECTED_MISSING',
14
+ 'PLATE_EXPECTED_MISSING',
15
+ 'MEDIA_UNREADABLE',
16
+ 'DEVICE_AUDIT_ERROR',
17
+ ];
18
+ export const THRESHOLDS = {
19
+ lastFrameStaleMs: 2_000,
20
+ mediaCoverageMin: 0.5,
21
+ longTrackMs: 5_000,
22
+ betterShotRatio: 1.5,
23
+ edgeFraction: 0.01,
24
+ faceMinTrackMs: 3_000,
25
+ plateMinTrackMs: 2_000,
26
+ fragmentMaxMs: 1_500,
27
+ fragmentNeighborWindowMs: 15_000,
28
+ };
29
+ /** Native sensor width the face-size estimate scales to (4K). */
30
+ const NATIVE_WIDTH_PX = 3_840;
31
+ /** Rough facial height as a fraction of a standing person's bbox height. */
32
+ const FACE_FRACTION_DENOMINATOR = 7;
33
+ export const isSynthetic = (t) => t.trackId.startsWith('pa-synth-') ||
34
+ t.source === 'synthetic' ||
35
+ t.source === 'sensor' ||
36
+ t.className === 'switch';
37
+ /** Detection-grid dimensions, estimated from positions and the normalised envelope. */
38
+ export function frameDims(track) {
39
+ let maxX = 0;
40
+ let maxY = 0;
41
+ for (const p of track.positions) {
42
+ maxX = Math.max(maxX, p.bbox.x + p.bbox.w);
43
+ maxY = Math.max(maxY, p.bbox.y + p.bbox.h);
44
+ }
45
+ const env = track.envelope;
46
+ const W = env?.maxX !== undefined && env.maxX > 0.05 ? maxX / env.maxX : Math.max(640, maxX);
47
+ const H = env?.maxY !== undefined && env.maxY > 0.05 ? maxY / env.maxY : Math.max(360, maxY);
48
+ return { W, H };
49
+ }
50
+ export function touchesEdge(b, W, H) {
51
+ const f = THRESHOLDS.edgeFraction;
52
+ return b.x <= W * f || b.y <= H * f || b.x + b.w >= W * (1 - f) || b.y + b.h >= H * (1 - f);
53
+ }
54
+ const seconds = (ms) => (ms / 1000).toFixed(1);
55
+ function faceVerdict(track, W, dur) {
56
+ const maxH = Math.max(...track.positions.map((p) => p.bbox.h), 0);
57
+ const detPx = maxH / FACE_FRACTION_DENOMINATOR;
58
+ const nativePx = detPx * (NATIVE_WIDTH_PX / W);
59
+ const verdict = nativePx >= 60
60
+ ? 'UNEXPECTED — well above native gate, investigate detector/step'
61
+ : nativePx >= 30
62
+ ? 'borderline vs native gate'
63
+ : 'likely below native gate (expected miss)';
64
+ return `no face held for ${seconds(dur)}s; est. face ~${detPx.toFixed(0)}px detection-space (~${nativePx.toFixed(0)}px native) — ${verdict}`;
65
+ }
66
+ /** The audit rules for one track. Pure: same input, same findings. */
67
+ export function analyzeTrack(input) {
68
+ const { track, media } = input;
69
+ const findings = [];
70
+ const flag = (code, detail) => {
71
+ findings.push({
72
+ deviceId: track.deviceId,
73
+ trackId: track.trackId,
74
+ className: track.className,
75
+ code,
76
+ detail,
77
+ });
78
+ };
79
+ if (media === null) {
80
+ flag('MEDIA_UNREADABLE', 'media index could not be read — media findings are unknown, not absent');
81
+ return findings;
82
+ }
83
+ const dur = track.lastSeen - track.firstSeen;
84
+ const pos = track.positions;
85
+ const { W, H } = frameDims(track);
86
+ const closed = track.active !== true;
87
+ const ofKind = (kind) => media.find((m) => m.kind === kind);
88
+ const ff = ofKind('firstFrame');
89
+ const lf = ofKind('lastFrame');
90
+ const thumb = ofKind('thumbnail');
91
+ if (media.length === 0)
92
+ flag('ZERO_MEDIA', `dur=${dur}ms positions=${pos.length} state=${track.state}`);
93
+ if (closed && media.length > 0) {
94
+ if (!ff)
95
+ flag('MISSING_FIRSTFRAME', `dur=${dur}ms media=${media.length}`);
96
+ if (!lf)
97
+ flag('MISSING_LASTFRAME', `dur=${dur}ms media=${media.length}`);
98
+ if (!thumb)
99
+ flag('MISSING_THUMBNAIL', `dur=${dur}ms media=${media.length}`);
100
+ }
101
+ if (input.ffEqualsLf === true)
102
+ flag('FF_EQ_LF', 'firstFrame and lastFrame byte-identical');
103
+ if (closed && lf && track.lastSeen - lf.timestamp > THRESHOLDS.lastFrameStaleMs) {
104
+ flag('LASTFRAME_STALE', `lastFrame ${seconds(track.lastSeen - lf.timestamp)}s before close`);
105
+ }
106
+ if (closed && dur >= THRESHOLDS.longTrackMs && media.length > 0) {
107
+ const lastMediaTs = Math.max(...media.map((m) => m.timestamp));
108
+ const coverage = (lastMediaTs - track.firstSeen) / dur;
109
+ if (coverage < THRESHOLDS.mediaCoverageMin) {
110
+ flag('MEDIA_STOPPED_EARLY', `captures ceased at ${(coverage * 100).toFixed(0)}% of a ${seconds(dur)}s track`);
111
+ }
112
+ }
113
+ if (thumb && pos.length > 2) {
114
+ const atThumb = pos.reduce((best, p) => Math.abs(p.timestamp - thumb.timestamp) < Math.abs(best.timestamp - thumb.timestamp)
115
+ ? p
116
+ : best);
117
+ const areaAtThumb = atThumb.bbox.w * atThumb.bbox.h;
118
+ if (touchesEdge(atThumb.bbox, W, H)) {
119
+ flag('BEST_AT_EDGE', `bbox ${JSON.stringify(atThumb.bbox)} touches frame edge at capture (grid ~${W.toFixed(0)}x${H.toFixed(0)}) — letterbox/cut risk`);
120
+ }
121
+ let better = null;
122
+ for (const p of pos) {
123
+ if (p.timestamp <= thumb.timestamp)
124
+ continue;
125
+ const area = p.bbox.w * p.bbox.h;
126
+ if (area >= areaAtThumb * THRESHOLDS.betterShotRatio && !touchesEdge(p.bbox, W, H)) {
127
+ if (!better || area > better.area)
128
+ better = { area, at: p.timestamp };
129
+ }
130
+ }
131
+ if (better) {
132
+ flag('BEST_SHOT_STALE', `thumbnail@+${seconds(thumb.timestamp - track.firstSeen)}s area=${areaAtThumb.toFixed(0)}; in-frame area=${better.area.toFixed(0)} (${(better.area / areaAtThumb).toFixed(1)}x) existed @+${seconds(better.at - track.firstSeen)}s`);
133
+ }
134
+ }
135
+ if (closed && pos.length > 2) {
136
+ const last = pos[pos.length - 1];
137
+ if (!touchesEdge(last.bbox, W, H) && dur >= THRESHOLDS.fragmentMaxMs) {
138
+ flag('ENDED_MID_FRAME', `last bbox ${JSON.stringify(last.bbox)} well inside ~${W.toFixed(0)}x${H.toFixed(0)} — early loss suspect (dur=${seconds(dur)}s)`);
139
+ }
140
+ }
141
+ if (closed && dur <= THRESHOLDS.fragmentMaxMs && track.state === 'entered') {
142
+ const sibling = input.siblings.find((o) => o.trackId !== track.trackId &&
143
+ o.className === track.className &&
144
+ Math.abs(o.firstSeen - track.lastSeen) <= THRESHOLDS.fragmentNeighborWindowMs);
145
+ flag('FRAGMENT_SUSPECT', `dur=${dur}ms never confirmed${sibling ? `; same-class sibling ${sibling.trackId.slice(0, 8)} within ${THRESHOLDS.fragmentNeighborWindowMs / 1000}s` : ''}`);
146
+ }
147
+ if (input.enrichment.face === 'missing')
148
+ flag('FACE_EXPECTED_MISSING', faceVerdict(track, W, dur));
149
+ if (input.enrichment.plate === 'missing') {
150
+ flag('PLATE_EXPECTED_MISSING', `no plate for ${seconds(dur)}s vehicle track`);
151
+ }
152
+ return findings;
153
+ }
154
+ export function qualifiesForFace(track, faceDevices) {
155
+ return (track.className === 'person' &&
156
+ faceDevices.has(track.deviceId) &&
157
+ track.lastSeen - track.firstSeen >= THRESHOLDS.faceMinTrackMs);
158
+ }
159
+ export function qualifiesForPlate(track, plateDevices) {
160
+ return (track.className === 'vehicle' &&
161
+ plateDevices.has(track.deviceId) &&
162
+ track.lastSeen - track.firstSeen >= THRESHOLDS.plateMinTrackMs);
163
+ }
@@ -0,0 +1,61 @@
1
+ /**
2
+ * The slices of hub payloads the ops tools actually read, validated at the
3
+ * boundary (a hub answer is external data). Loose objects: fields we do not name
4
+ * are carried, not rejected — the hub adds fields faster than this file.
5
+ */
6
+ import { z } from 'zod';
7
+ export interface TrackBBox {
8
+ x: number;
9
+ y: number;
10
+ w: number;
11
+ h: number;
12
+ }
13
+ export interface TrackPosition {
14
+ timestamp: number;
15
+ bbox: TrackBBox;
16
+ }
17
+ export interface TrackEnvelope {
18
+ maxX?: number;
19
+ maxY?: number;
20
+ }
21
+ export interface Track {
22
+ trackId: string;
23
+ deviceId: number;
24
+ className: string;
25
+ source?: string;
26
+ firstSeen: number;
27
+ lastSeen: number;
28
+ state?: string;
29
+ active?: boolean;
30
+ positions: TrackPosition[];
31
+ envelope?: TrackEnvelope;
32
+ }
33
+ export declare const TrackSchema: z.ZodType<Track>;
34
+ export interface RecentTracksPage {
35
+ tracks: Track[];
36
+ nextCursor?: string | null;
37
+ }
38
+ export declare const RecentTracksPageSchema: z.ZodType<RecentTracksPage>;
39
+ export interface MediaInfo {
40
+ mediaId: number;
41
+ kind: string;
42
+ sizeBytes: number;
43
+ timestamp: number;
44
+ }
45
+ export declare const MediaInfoSchema: z.ZodType<MediaInfo>;
46
+ export interface MediaWithBytes extends MediaInfo {
47
+ base64?: string;
48
+ }
49
+ export declare const MediaWithBytesSchema: z.ZodType<MediaWithBytes>;
50
+ export declare const CameraStatusSchema: z.ZodType<{
51
+ deviceId: number;
52
+ }>;
53
+ export interface LogDestinationProvider {
54
+ addonId: string;
55
+ isActive?: boolean;
56
+ mode?: string;
57
+ }
58
+ export declare const LogDestinationProviderSchema: z.ZodType<LogDestinationProvider>;
59
+ /** Parse a hub answer, naming the method on failure instead of throwing a bare zod dump. */
60
+ export declare function parseWire<S extends z.ZodType>(schema: S, value: unknown, label: string): z.infer<S>;
61
+ //# sourceMappingURL=wire.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"wire.d.ts","sourceRoot":"","sources":["../../../src/mcp/ops/wire.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAA;AASvB,MAAM,WAAW,SAAS;IACxB,CAAC,EAAE,MAAM,CAAA;IACT,CAAC,EAAE,MAAM,CAAA;IACT,CAAC,EAAE,MAAM,CAAA;IACT,CAAC,EAAE,MAAM,CAAA;CACV;AAED,MAAM,WAAW,aAAa;IAC5B,SAAS,EAAE,MAAM,CAAA;IACjB,IAAI,EAAE,SAAS,CAAA;CAChB;AAED,MAAM,WAAW,aAAa;IAC5B,IAAI,CAAC,EAAE,MAAM,CAAA;IACb,IAAI,CAAC,EAAE,MAAM,CAAA;CACd;AAED,MAAM,WAAW,KAAK;IACpB,OAAO,EAAE,MAAM,CAAA;IACf,QAAQ,EAAE,MAAM,CAAA;IAChB,SAAS,EAAE,MAAM,CAAA;IACjB,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,SAAS,EAAE,MAAM,CAAA;IACjB,QAAQ,EAAE,MAAM,CAAA;IAChB,KAAK,CAAC,EAAE,MAAM,CAAA;IACd,MAAM,CAAC,EAAE,OAAO,CA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C,CAWZ"}
@@ -0,0 +1,66 @@
1
+ /**
2
+ * The slices of hub payloads the ops tools actually read, validated at the
3
+ * boundary (a hub answer is external data). Loose objects: fields we do not name
4
+ * are carried, not rejected — the hub adds fields faster than this file.
5
+ */
6
+ import { z } from 'zod';
7
+ const BBoxSchema = z.object({
8
+ x: z.number(),
9
+ y: z.number(),
10
+ w: z.number(),
11
+ h: z.number(),
12
+ });
13
+ const trackSchema = z.looseObject({
14
+ trackId: z.string(),
15
+ deviceId: z.number(),
16
+ className: z.string(),
17
+ source: z.string().optional(),
18
+ firstSeen: z.number(),
19
+ lastSeen: z.number(),
20
+ state: z.string().optional(),
21
+ active: z.boolean().optional(),
22
+ positions: z
23
+ .array(z.looseObject({ timestamp: z.number(), bbox: BBoxSchema }))
24
+ .optional()
25
+ .default([]),
26
+ envelope: z
27
+ .looseObject({
28
+ maxX: z.number().optional(),
29
+ maxY: z.number().optional(),
30
+ })
31
+ .optional(),
32
+ });
33
+ export const TrackSchema = trackSchema;
34
+ export const RecentTracksPageSchema = z.looseObject({
35
+ tracks: z.array(trackSchema),
36
+ nextCursor: z.string().nullable().optional(),
37
+ });
38
+ const mediaInfoSchema = z.looseObject({
39
+ mediaId: z.number(),
40
+ kind: z.string(),
41
+ sizeBytes: z.number(),
42
+ timestamp: z.number(),
43
+ });
44
+ export const MediaInfoSchema = mediaInfoSchema;
45
+ export const MediaWithBytesSchema = mediaInfoSchema.extend({
46
+ base64: z.string().optional(),
47
+ });
48
+ export const CameraStatusSchema = z.looseObject({
49
+ deviceId: z.number(),
50
+ });
51
+ export const LogDestinationProviderSchema = z.looseObject({
52
+ addonId: z.string(),
53
+ isActive: z.boolean().optional(),
54
+ mode: z.string().optional(),
55
+ });
56
+ /** Parse a hub answer, naming the method on failure instead of throwing a bare zod dump. */
57
+ export function parseWire(schema, value, label) {
58
+ const result = schema.safeParse(value);
59
+ if (!result.success) {
60
+ throw new Error(`${label}: unexpected answer shape (${result.error.issues
61
+ .slice(0, 3)
62
+ .map((i) => `${i.path.join('.')}: ${i.message}`)
63
+ .join('; ')}) — the hub and this tool may be on different versions`);
64
+ }
65
+ return result.data;
66
+ }
@@ -0,0 +1,16 @@
1
+ /**
2
+ * The gate every ops call passes before a byte leaves the machine:
3
+ * query-only, tier-checked, and never a credential-bearing method.
4
+ */
5
+ import type { CredentialTier } from '../hub/credentials.js';
6
+ import type { ApiIndex, ApiMethod } from './api-index.js';
7
+ export type GateDecision = {
8
+ readonly allowed: true;
9
+ readonly method: ApiMethod;
10
+ } | {
11
+ readonly allowed: false;
12
+ readonly reason: string;
13
+ };
14
+ export declare function isSecretBearing(methodPath: string): boolean;
15
+ export declare function gateQuery(index: ApiIndex, methodPath: string, tier: CredentialTier): GateDecision;
16
+ //# sourceMappingURL=query-gate.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"query-gate.d.ts","sourceRoot":"","sources":["../../src/mcp/query-gate.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAA;AAC3D,OAAO,KAAK,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAA;AAEzD,MAAM,MAAM,YAAY,GACpB;IAAE,QAAQ,CAAC,OAAO,EAAE,IAAI,CAAC;IAAC,QAAQ,CAAC,MAAM,EAAE,SAAS,CAAA;CAAE,GACtD;IAAE,QAAQ,CAAC,OAAO,EAAE,KAAK,CAAC;IAAC,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAA;CAAE,CAAA;AAWxD,wBAAgB,eAAe,CAAC,UAAU,EAAE,MAAM,GAAG,OAAO,CAI3D;AAED,wBAAgB,SAAS,CAAC,KAAK,EAAE,QAAQ,EAAE,UAAU,EAAE,MAAM,EAAE,IAAI,EAAE,cAAc,GAAG,YAAY,CA2BjG"}
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Methods that return secret material even though they are `query` and
3
+ * admin-gated: the keychain's plaintext resolver and reveal, a camera's
4
+ * credentials, anything named for a secret. The ops toolset never reads them
5
+ * (D783: a tool, like a log line, is not a place a secret may land).
6
+ */
7
+ const SECRET_BEARING_ROUTERS = new Set(['keychain', 'keychainAdmin']);
8
+ const SECRET_BEARING_NAME = /secret|password|passphrase|recoverykey|reveal|getcredentials|jwt/i;
9
+ export function isSecretBearing(methodPath) {
10
+ const [router = '', ...rest] = methodPath.split('.');
11
+ if (SECRET_BEARING_ROUTERS.has(router))
12
+ return true;
13
+ return SECRET_BEARING_NAME.test(rest.join('.'));
14
+ }
15
+ export function gateQuery(index, methodPath, tier) {
16
+ const method = index.get(methodPath);
17
+ if (!method) {
18
+ return {
19
+ allowed: false,
20
+ reason: `${methodPath} is not in the generated API index (docs/reference/api.md) — check the path, or run \`npm run docs:generate\` if it is new.`,
21
+ };
22
+ }
23
+ if (method.kind !== 'query') {
24
+ return {
25
+ allowed: false,
26
+ reason: `${methodPath} is a ${method.kind}; the ops toolset is read-only and only calls queries.`,
27
+ };
28
+ }
29
+ if (isSecretBearing(methodPath)) {
30
+ return {
31
+ allowed: false,
32
+ reason: `${methodPath} returns secret material; the ops toolset never reads it.`,
33
+ };
34
+ }
35
+ if (method.auth === 'admin' && tier !== 'admin') {
36
+ return {
37
+ allowed: false,
38
+ reason: `${methodPath} is admin-tier and this credential is not admin-scoped. Log in with an admin account via \`camstack login\`.`,
39
+ };
40
+ }
41
+ return { allowed: true, method };
42
+ }
@@ -0,0 +1,33 @@
1
+ /**
2
+ * What may leave an ops call: secret fields redacted by their DECLARATION, and
3
+ * the payload bounded so a media blob or a 10k-row list never floods a context.
4
+ *
5
+ * Declarations (the repository's own, D783/D787):
6
+ * - a stored marker `{ "$secret": "secret://…", "v": 1 }` (or its UI view);
7
+ * - a config-UI field declared `type: 'password'` or `secret: true` — its
8
+ * `value`/`default` is the secret, whatever the key is called.
9
+ * The output layer (`text()`) then adds the name/pattern scrub on top.
10
+ */
11
+ export declare const REDACTED = "[SECRET]";
12
+ /** A copy of `value` with every declared secret replaced; the input is untouched. */
13
+ export declare function redactDeclaredSecrets(value: unknown): unknown;
14
+ export interface TruncateLimits {
15
+ readonly maxItems: number;
16
+ readonly maxStringChars: number;
17
+ readonly maxTotalChars: number;
18
+ }
19
+ export declare const DEFAULT_LIMITS: TruncateLimits;
20
+ export interface Truncated {
21
+ readonly truncated: true;
22
+ readonly reason: string;
23
+ readonly totalChars: number;
24
+ readonly preview: string;
25
+ }
26
+ /**
27
+ * Bound a payload: long strings (a base64 frame) are cut, long arrays are
28
+ * capped, and a result still over the total budget becomes a labelled preview.
29
+ */
30
+ export declare function truncateOutput(value: unknown, limits?: TruncateLimits): unknown;
31
+ /** Redact then bound — the only way a hub payload becomes tool output. */
32
+ export declare function toToolOutput(value: unknown, limits?: TruncateLimits): unknown;
33
+ //# sourceMappingURL=redact.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"redact.d.ts","sourceRoot":"","sources":["../../src/mcp/redact.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,eAAO,MAAM,QAAQ,aAAa,CAAA;AAUlC,qFAAqF;AACrF,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,OAAO,GAAG,OAAO,CAW7D;AAED,MAAM,WAAW,cAAc;IAC7B,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAA;IACzB,QAAQ,CAAC,cAAc,EAAE,MAAM,CAAA;IAC/B,QAAQ,CAAC,aAAa,EAAE,MAAM,CAAA;CAC/B;AAED,eAAO,MAAM,cAAc,EAAE,cAI5B,CAAA;AAED,MAAM,WAAW,SAAS;IACxB,QAAQ,CAAC,SAAS,EAAE,IAAI,CAAA;IACxB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAA;IACvB,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAA;IAC3B,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAA;CACzB;AAsBD;;;GAGG;AACH,wBAAgB,cAAc,CAAC,KAAK,EAAE,OAAO,EAAE,MAAM,GAAE,cAA+B,GAAG,OAAO,CAU/F;AAED,0EAA0E;AAC1E,wBAAgB,YAAY,CAAC,KAAK,EAAE,OAAO,EAAE,MAAM,GAAE,cAA+B,GAAG,OAAO,CAE7F"}
@@ -0,0 +1,78 @@
1
+ /**
2
+ * What may leave an ops call: secret fields redacted by their DECLARATION, and
3
+ * the payload bounded so a media blob or a 10k-row list never floods a context.
4
+ *
5
+ * Declarations (the repository's own, D783/D787):
6
+ * - a stored marker `{ "$secret": "secret://…", "v": 1 }` (or its UI view);
7
+ * - a config-UI field declared `type: 'password'` or `secret: true` — its
8
+ * `value`/`default` is the secret, whatever the key is called.
9
+ * The output layer (`text()`) then adds the name/pattern scrub on top.
10
+ */
11
+ export const REDACTED = '[SECRET]';
12
+ function isRecord(value) {
13
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
14
+ }
15
+ function isDeclaredSecretField(value) {
16
+ return value['type'] === 'password' || value['secret'] === true;
17
+ }
18
+ /** A copy of `value` with every declared secret replaced; the input is untouched. */
19
+ export function redactDeclaredSecrets(value) {
20
+ if (Array.isArray(value))
21
+ return value.map((v) => redactDeclaredSecrets(v));
22
+ if (!isRecord(value))
23
+ return value;
24
+ if (Object.prototype.hasOwnProperty.call(value, '$secret'))
25
+ return REDACTED;
26
+ const declared = isDeclaredSecretField(value);
27
+ const out = {};
28
+ for (const [key, child] of Object.entries(value)) {
29
+ out[key] =
30
+ declared && (key === 'value' || key === 'default') ? REDACTED : redactDeclaredSecrets(child);
31
+ }
32
+ return out;
33
+ }
34
+ export const DEFAULT_LIMITS = {
35
+ maxItems: 100,
36
+ maxStringChars: 1_000,
37
+ maxTotalChars: 30_000,
38
+ };
39
+ function shrink(value, limits) {
40
+ if (typeof value === 'string') {
41
+ return value.length > limits.maxStringChars
42
+ ? `${value.slice(0, 80)}… [${value.length - 80} more chars omitted]`
43
+ : value;
44
+ }
45
+ if (Array.isArray(value)) {
46
+ const head = value.slice(0, limits.maxItems).map((v) => shrink(v, limits));
47
+ return value.length > limits.maxItems
48
+ ? [...head, { _omitted: `${value.length - limits.maxItems} more items` }]
49
+ : head;
50
+ }
51
+ if (isRecord(value)) {
52
+ const out = {};
53
+ for (const [k, v] of Object.entries(value))
54
+ out[k] = shrink(v, limits);
55
+ return out;
56
+ }
57
+ return value;
58
+ }
59
+ /**
60
+ * Bound a payload: long strings (a base64 frame) are cut, long arrays are
61
+ * capped, and a result still over the total budget becomes a labelled preview.
62
+ */
63
+ export function truncateOutput(value, limits = DEFAULT_LIMITS) {
64
+ const shrunk = shrink(value, limits);
65
+ const json = JSON.stringify(shrunk) ?? 'null';
66
+ if (json.length <= limits.maxTotalChars)
67
+ return shrunk;
68
+ return {
69
+ truncated: true,
70
+ reason: `result is ${json.length} chars, over the ${limits.maxTotalChars} budget — narrow the query (limit, window, ids)`,
71
+ totalChars: json.length,
72
+ preview: json.slice(0, limits.maxTotalChars),
73
+ };
74
+ }
75
+ /** Redact then bound — the only way a hub payload becomes tool output. */
76
+ export function toToolOutput(value, limits = DEFAULT_LIMITS) {
77
+ return truncateOutput(redactDeclaredSecrets(value), limits);
78
+ }
@@ -0,0 +1,4 @@
1
+ /** Redact secrets and credential paths from tool outputs before they leave the MCP. */
2
+ export declare function scrubSecrets(text: string): string;
3
+ export declare function scrubValue(value: unknown): unknown;
4
+ //# sourceMappingURL=scrub.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"scrub.d.ts","sourceRoot":"","sources":["../../src/mcp/scrub.ts"],"names":[],"mappings":"AAAA,uFAAuF;AAWvF,wBAAgB,YAAY,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAMjD;AAMD,wBAAgB,UAAU,CAAC,KAAK,EAAE,OAAO,GAAG,OAAO,CA0BlD"}
@@ -0,0 +1,49 @@
1
+ /** Redact secrets and credential paths from tool outputs before they leave the MCP. */
2
+ const SECRET_PATTERNS = [
3
+ /\bglsa_[A-Za-z0-9_-]{10,}\b/g,
4
+ /\beyJ[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\b/g,
5
+ /\bBearer\s+[A-Za-z0-9._\-+=/]{20,}\b/gi,
6
+ /(?:password|passwd|secret|token|api[_-]?key)\s*[:=]\s*['"]?[^\s'"]{8,}/gi,
7
+ /(?:\/Users\/[^/\s]+\/\.camstack\/[^\s'"]+)/g,
8
+ /(?:~\/\.camstack\/[^\s'"]+)/g,
9
+ ];
10
+ export function scrubSecrets(text) {
11
+ let out = text;
12
+ for (const re of SECRET_PATTERNS) {
13
+ out = out.replace(re, '[REDACTED]');
14
+ }
15
+ return out;
16
+ }
17
+ function isRecord(value) {
18
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
19
+ }
20
+ export function scrubValue(value) {
21
+ if (typeof value === 'string')
22
+ return scrubSecrets(value);
23
+ if (value === null || value === undefined)
24
+ return value;
25
+ if (Array.isArray(value))
26
+ return value.map((v) => scrubValue(v));
27
+ if (isRecord(value)) {
28
+ const out = {};
29
+ for (const [k, v] of Object.entries(value)) {
30
+ const keyLower = k.toLowerCase();
31
+ // `confirm_token` is the mutation gate's one-shot, argument-bound,
32
+ // short-lived handle — the operator must be able to read it back.
33
+ if (k === 'confirm_token') {
34
+ out[k] = v;
35
+ }
36
+ else if (keyLower.includes('token') ||
37
+ keyLower.includes('password') ||
38
+ keyLower.includes('secret') ||
39
+ keyLower === 'authorization') {
40
+ out[k] = '[REDACTED]';
41
+ }
42
+ else {
43
+ out[k] = scrubValue(v);
44
+ }
45
+ }
46
+ return out;
47
+ }
48
+ return value;
49
+ }
@@ -0,0 +1,14 @@
1
+ export declare function text(value: unknown): {
2
+ content: {
3
+ type: 'text';
4
+ text: string;
5
+ }[];
6
+ };
7
+ export declare function textError(message: string): {
8
+ content: {
9
+ type: 'text';
10
+ text: string;
11
+ }[];
12
+ isError: true;
13
+ };
14
+ //# sourceMappingURL=text.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"text.d.ts","sourceRoot":"","sources":["../../src/mcp/text.ts"],"names":[],"mappings":"AAEA,wBAAgB,IAAI,CAAC,KAAK,EAAE,OAAO,GAAG;IAAE,OAAO,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,CAAA;KAAE,EAAE,CAAA;CAAE,CAOlF;AAED,wBAAgB,SAAS,CAAC,OAAO,EAAE,MAAM,GAAG;IAC1C,OAAO,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,CAAA;KAAE,EAAE,CAAA;IACzC,OAAO,EAAE,IAAI,CAAA;CACd,CAKA"}
@@ -0,0 +1,14 @@
1
+ import { scrubSecrets, scrubValue } from './scrub.js';
2
+ export function text(value) {
3
+ const cleaned = scrubValue(value);
4
+ const body = typeof cleaned === 'string' ? scrubSecrets(cleaned) : JSON.stringify(cleaned, null, 2);
5
+ return {
6
+ content: [{ type: 'text', text: scrubSecrets(body) }],
7
+ };
8
+ }
9
+ export function textError(message) {
10
+ return {
11
+ content: [{ type: 'text', text: scrubSecrets(message) }],
12
+ isError: true,
13
+ };
14
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@camstack/develop",
3
- "version": "0.1.39",
3
+ "version": "0.1.40",
4
4
  "description": "CamStack developer tooling — catalogue, scaffold, validate, and example lookup shared by the CLI and MCP server.",
5
5
  "keywords": [
6
6
  "camstack",
@@ -57,6 +57,7 @@
57
57
  },
58
58
  "dependencies": {
59
59
  "@camstack/types": "*",
60
- "multicast-dns": "^7.2.5"
60
+ "multicast-dns": "^7.2.5",
61
+ "zod": "^4.3.6"
61
62
  }
62
63
  }