@camstack/develop 0.1.4 → 0.1.6

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.
@@ -1 +1 @@
1
- {"version":3,"file":"credentials.d.ts","sourceRoot":"","sources":["../../src/hub/credentials.ts"],"names":[],"mappings":"AA6BA,MAAM,MAAM,gBAAgB,GAAG,MAAM,GAAG,YAAY,GAAG,aAAa,GAAG,KAAK,GAAG,SAAS,CAAA;AAExF,2EAA2E;AAC3E,MAAM,MAAM,cAAc,GAAG,OAAO,GAAG,WAAW,CAAA;AAElD,eAAO,MAAM,kBAAkB,SAAS,CAAA;AAExC,+EAA+E;AAC/E,wBAAgB,cAAc,CAAC,KAAK,EAAE,MAAM,GAAG,cAAc,CAE5D;AAED,MAAM,WAAW,mBAAmB;IAClC,QAAQ,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAA;IACnC,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAA;IACtB,QAAQ,CAAC,MAAM,EAAE,gBAAgB,CAAA;IACjC,oFAAoF;IACpF,QAAQ,CAAC,IAAI,EAAE,cAAc,CAAA;IAC7B,sEAAsE;IACtE,QAAQ,CAAC,OAAO,CAAC,EAAE,MAAM,CAAA;CAC1B;AAED,MAAM,WAAW,iBAAiB;IAChC,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAA;IACvB,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAA;CACvB;AAED,MAAM,WAAW,gBAAgB;IAC/B,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,CAAA;IACxB,QAAQ,CAAC,KAAK,CAAC,EAAE,MAAM,CAAA;IACvB,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,CAAA;IAC3B,0FAA0F;IAC1F,QAAQ,CAAC,cAAc,CAAC,EAAE,MAAM,CAAA;IAChC,QAAQ,CAAC,GAAG,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CA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AAM,EAAE,gBAAgB,GAAG,mBAAmB,CAgBhF;AA4BD;;;GAGG;AACH,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,gBAAgB,GAAG,MAAM,GAAG,IAAI,CAGxF;AAED,qFAAqF;AACrF,wBAAgB,YAAY,CAC1B,OAAO,EAAE,MAAM,EACf,MAAM,EAAE,MAAM,EACd,MAAM,EAAE,gBAAgB,GAAG,SAAS,GACnC,MAAM,CAGR"}
@@ -26,6 +26,7 @@
26
26
  * The caller applies its own default when none of these is set.
27
27
  */
28
28
  import * as fs from 'node:fs';
29
+ import { normalizeHubAddress } from './hub-address.js';
29
30
  export const ADMIN_TOKEN_PREFIX = 'csa_';
30
31
  /** The tier a token buys. Prefix only: the hub still decides on every call. */
31
32
  export function credentialTier(token) {
@@ -102,7 +103,8 @@ export function resolveCredentials(inputs) {
102
103
  // Key the session lookup on the hub actually targeted: with no explicit
103
104
  // server, `loadSession` falls back to the NEWEST session file, which may
104
105
  // belong to a different hub than $CAMSTACK_SERVER.
105
- const targeted = inputs.server ?? env['CAMSTACK_SERVER'] ?? file?.server;
106
+ const typed = inputs.server ?? env['CAMSTACK_SERVER'];
107
+ const targeted = typed ? normalizeHubAddress(typed) : file?.server;
106
108
  const session = inputs.loadSession(targeted);
107
109
  const server = targeted ?? session?.server;
108
110
  const adminFile = inputs.adminTokenFile ? readTokenFile(inputs.adminTokenFile) : null;
@@ -0,0 +1,24 @@
1
+ /**
2
+ * The ONE parser for "which hub": every tool that takes a server (the CLI's
3
+ * login/whoami/deploy/dev/watch, `scripts/hub/hub.mjs`, the operator MCP)
4
+ * passes its input through {@link normalizeHubAddress}, so `192.168.1.50`,
5
+ * `hub.local:4443` and `https://[fe80::1]:4443/` all name the same canonical
6
+ * `https://<host>:<port>` and a typo fails the same way everywhere.
7
+ *
8
+ * The hub API is https only (self-signed on the LAN, trusted per hub): an
9
+ * `http://` address is refused with a message instead of being rewritten, so
10
+ * the operator learns the scheme rather than silently talking to another port.
11
+ */
12
+ export declare const DEFAULT_HUB_PORT = 4443;
13
+ export declare class HubAddressError extends Error {
14
+ constructor(message: string);
15
+ }
16
+ /**
17
+ * `https://<host>:<port>` (default port 4443, scheme https, lower-case host,
18
+ * no path or trailing slash). Throws {@link HubAddressError} on an empty value,
19
+ * an `http://` or other scheme, a bad port or an unparsable host.
20
+ */
21
+ export declare function normalizeHubAddress(input: string): string;
22
+ /** {@link normalizeHubAddress} for a prompt validator: the message, or `undefined` when valid. */
23
+ export declare function validateHubAddress(input: string): string | undefined;
24
+ //# sourceMappingURL=hub-address.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hub-address.d.ts","sourceRoot":"","sources":["../../src/hub/hub-address.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,eAAO,MAAM,gBAAgB,OAAO,CAAA;AAEpC,qBAAa,eAAgB,SAAQ,KAAK;gBAC5B,OAAO,EAAE,MAAM;CAI5B;AAgCD;;;;GAIG;AACH,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CA4BzD;AAED,kGAAkG;AAClG,wBAAgB,kBAAkB,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAOpE"}
@@ -0,0 +1,87 @@
1
+ /**
2
+ * The ONE parser for "which hub": every tool that takes a server (the CLI's
3
+ * login/whoami/deploy/dev/watch, `scripts/hub/hub.mjs`, the operator MCP)
4
+ * passes its input through {@link normalizeHubAddress}, so `192.168.1.50`,
5
+ * `hub.local:4443` and `https://[fe80::1]:4443/` all name the same canonical
6
+ * `https://<host>:<port>` and a typo fails the same way everywhere.
7
+ *
8
+ * The hub API is https only (self-signed on the LAN, trusted per hub): an
9
+ * `http://` address is refused with a message instead of being rewritten, so
10
+ * the operator learns the scheme rather than silently talking to another port.
11
+ */
12
+ export const DEFAULT_HUB_PORT = 4443;
13
+ export class HubAddressError extends Error {
14
+ constructor(message) {
15
+ super(message);
16
+ this.name = 'HubAddressError';
17
+ }
18
+ }
19
+ const SCHEME = /^([a-z][a-z0-9+.-]*):\/\//i;
20
+ const BRACKETED = /^\[([^\]]+)\](?::(\d+))?$/;
21
+ const HOST_PORT = /^([^:]+)(?::(\d+))?$/;
22
+ function parsePort(raw, input) {
23
+ if (raw === undefined)
24
+ return DEFAULT_HUB_PORT;
25
+ const port = Number.parseInt(raw, 10);
26
+ if (port < 1 || port > 65535) {
27
+ throw new HubAddressError(`"${input}": port ${raw} is out of range (1-65535).`);
28
+ }
29
+ return port;
30
+ }
31
+ function splitAuthority(authority, input) {
32
+ const bracketed = BRACKETED.exec(authority);
33
+ if (bracketed)
34
+ return { host: `[${bracketed[1]}]`, port: parsePort(bracketed[2], input) };
35
+ // A bare IPv6 literal (two or more colons) carries no port: brackets are needed for that.
36
+ if ((authority.match(/:/g) ?? []).length >= 2) {
37
+ return { host: `[${authority}]`, port: DEFAULT_HUB_PORT };
38
+ }
39
+ const plain = HOST_PORT.exec(authority);
40
+ if (!plain)
41
+ throw new HubAddressError(`"${input}" is not a hub address.`);
42
+ return { host: plain[1], port: parsePort(plain[2], input) };
43
+ }
44
+ /**
45
+ * `https://<host>:<port>` (default port 4443, scheme https, lower-case host,
46
+ * no path or trailing slash). Throws {@link HubAddressError} on an empty value,
47
+ * an `http://` or other scheme, a bad port or an unparsable host.
48
+ */
49
+ export function normalizeHubAddress(input) {
50
+ const trimmed = input.trim();
51
+ if (trimmed === '')
52
+ throw new HubAddressError('The hub address is empty.');
53
+ const scheme = SCHEME.exec(trimmed);
54
+ if (scheme) {
55
+ const name = scheme[1].toLowerCase();
56
+ if (name === 'http') {
57
+ throw new HubAddressError(`"${trimmed}": the hub API is https. Use https://<host>:${DEFAULT_HUB_PORT} (or just <host>).`);
58
+ }
59
+ if (name !== 'https') {
60
+ throw new HubAddressError(`"${trimmed}": unsupported scheme "${name}", the hub API is https.`);
61
+ }
62
+ }
63
+ const rest = scheme ? trimmed.slice(scheme[0].length) : trimmed;
64
+ const authority = rest.split(/[/?#]/, 1)[0] ?? '';
65
+ if (authority === '' || authority.includes('@')) {
66
+ throw new HubAddressError(`"${trimmed}" is not a hub address (expected host[:port]).`);
67
+ }
68
+ const { host, port } = splitAuthority(authority, trimmed);
69
+ let hostname;
70
+ try {
71
+ hostname = new URL(`https://${host}`).hostname;
72
+ }
73
+ catch {
74
+ throw new HubAddressError(`"${trimmed}": "${host}" is not a valid host name or address.`);
75
+ }
76
+ return `https://${hostname}:${port}`;
77
+ }
78
+ /** {@link normalizeHubAddress} for a prompt validator: the message, or `undefined` when valid. */
79
+ export function validateHubAddress(input) {
80
+ try {
81
+ normalizeHubAddress(input);
82
+ return undefined;
83
+ }
84
+ catch (err) {
85
+ return err instanceof HubAddressError ? err.message : String(err);
86
+ }
87
+ }
@@ -1 +1 @@
1
- {"version":3,"file":"hub-url.d.ts","sourceRoot":"","sources":["../../src/hub/hub-url.ts"],"names":[],"mappings":"AAaA,MAAM,WAAW,YAAY;IAC3B,QAAQ,CAAC,QAAQ,CAAC,EAAE,MAAM,CAAA;IAC1B,QAAQ,CAAC,GAAG,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,CAAC,CAAA;IAC3D,iEAAiE;IACjE,QAAQ,CAAC,aAAa,CAAC,EAAE,MAAM,CAAA;IAC/B,QAAQ,CAAC,OAAO,CAAC,EAAE;QAAE,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAA;KAAE,GAAG,IAAI,CAAA;CACtD;AAED,MAAM,MAAM,YAAY,GAAG,MAAM,GAAG,KAAK,GAAG,YAAY,GAAG,SAAS,CAAA;AAEpE,MAAM,WAAW,cAAc;IAC7B,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAA;IACpB,QAAQ,CAAC,MAAM,EAAE,YAAY,CAAA;CAC9B;AAiBD,4DAA4D;AAC5D,wBAAgB,aAAa,CAAC,MAAM,EAAE,YAAY,GAAG,cAAc,GAAG,SAAS,CAW9E"}
1
+ {"version":3,"file":"hub-url.d.ts","sourceRoot":"","sources":["../../src/hub/hub-url.ts"],"names":[],"mappings":"AAkBA,MAAM,WAAW,YAAY;IAC3B,QAAQ,CAAC,QAAQ,CAAC,EAAE,MAAM,CAAA;IAC1B,QAAQ,CAAC,GAAG,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,CAAC,CAAA;IAC3D,iEAAiE;IACjE,QAAQ,CAAC,aAAa,CAAC,EAAE,MAAM,CAAA;IAC/B,QAAQ,CAAC,OAAO,CAAC,EAAE;QAAE,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAA;KAAE,GAAG,IAAI,CAAA;CACtD;AAED,MAAM,MAAM,YAAY,GAAG,MAAM,GAAG,KAAK,GAAG,YAAY,GAAG,SAAS,CAAA;AAEpE,MAAM,WAAW,cAAc;IAC7B,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAA;IACpB,QAAQ,CAAC,MAAM,EAAE,YAAY,CAAA;CAC9B;AAuBD,4DAA4D;AAC5D,wBAAgB,aAAa,CAAC,MAAM,EAAE,YAAY,GAAG,cAAc,GAAG,SAAS,CAW9E"}
@@ -7,10 +7,20 @@
7
7
  * 3. `$CAMSTACK_SERVER` (the CLI's name for the same thing)
8
8
  * 4. `<workspace>/scratchpad/.hub-url` (gitignored, one line)
9
9
  * 5. the cached `camstack login` session's server
10
+ *
11
+ * Sources 1-4 are operator-typed, so each goes through `normalizeHubAddress`
12
+ * (`192.168.1.50` -> `https://192.168.1.50:4443`); a malformed value throws a
13
+ * `HubAddressError` rather than being used as written.
10
14
  */
11
15
  import * as fs from 'node:fs';
12
16
  import * as path from 'node:path';
17
+ import { normalizeHubAddress } from './hub-address.js';
13
18
  function clean(value) {
19
+ const trimmed = value?.trim();
20
+ return trimmed ? normalizeHubAddress(trimmed) : undefined;
21
+ }
22
+ /** The session's server as saved: already canonical, never re-parsed. */
23
+ function cleanSession(value) {
14
24
  const trimmed = value?.trim().replace(/\/+$/, '');
15
25
  return trimmed ? trimmed : undefined;
16
26
  }
@@ -37,7 +47,7 @@ export function resolveHubUrl(inputs) {
37
47
  const scratch = readScratchpadHubUrl(inputs.workspaceRoot);
38
48
  if (scratch)
39
49
  return { url: scratch, source: 'scratchpad' };
40
- const session = clean(inputs.session?.server);
50
+ const session = cleanSession(inputs.session?.server);
41
51
  if (session)
42
52
  return { url: session, source: 'session' };
43
53
  return undefined;
@@ -8,6 +8,8 @@ export interface SessionFile {
8
8
  target: string;
9
9
  }[];
10
10
  readonly createdAt: number;
11
+ /** Last time a command used this session (`touchSession`); absent on older files. */
12
+ readonly lastUsedAt?: number;
11
13
  }
12
14
  /** Where the cache lives; injectable so a test never touches the real home. */
13
15
  export declare function defaultSessionDir(): string;
@@ -26,6 +28,19 @@ export declare function adminTokenFileForServer(serverUrl: string, dir?: string)
26
28
  * file for `serverUrl`.
27
29
  */
28
30
  export declare function findAdminTokenFile(serverUrl: string | undefined, env?: Readonly<Record<string, string | undefined>>, dir?: string): string | undefined;
31
+ /** When a session was last used: `lastUsedAt`, else when it was created. */
32
+ export declare function sessionRecency(session: SessionFile): number;
33
+ /**
34
+ * Every readable saved session, most recently used first (ties: file mtime).
35
+ * A corrupt or partial file is skipped, never fatal.
36
+ */
37
+ export declare function listSessions(dir?: string): readonly SessionFile[];
38
+ /**
39
+ * THE default-session rule, used by every command that is given no server:
40
+ * 1. the session of `$CAMSTACK_SERVER`, when one is set and saved;
41
+ * 2. otherwise the most recently used session (`lastUsedAt`, else `createdAt`).
42
+ */
43
+ export declare function defaultSession(sessions: readonly SessionFile[], env?: Readonly<Record<string, string | undefined>>): SessionFile | null;
29
44
  /**
30
45
  * Shape check for a cached session blob. A partial or corrupted cache file
31
46
  * (e.g. after a crashed login) is treated as "no session" instead of crashing
@@ -34,5 +49,7 @@ export declare function findAdminTokenFile(serverUrl: string | undefined, env?:
34
49
  export declare function isSessionFile(value: unknown): value is SessionFile;
35
50
  export declare function loadSession(serverUrl?: string, dir?: string): SessionFile | null;
36
51
  export declare function saveSession(session: SessionFile, dir?: string): string;
52
+ /** Record that a command just used this session; best effort, never throws. */
53
+ export declare function touchSession(serverUrl: string, dir?: string, now?: number): void;
37
54
  export declare function clearSession(serverUrl: string, dir?: string): boolean;
38
55
  //# sourceMappingURL=session-store.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"session-store.d.ts","sourceRoot":"","sources":["../../src/hub/session-store.ts"],"names":[],"mappings":"AAWA,MAAM,WAAW,WAAW;IAC1B,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAA;IACvB,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAA;IACzB,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAA;IACxB,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAA;IACtB,QAAQ,CAAC,MAAM,EAAE,SAAS;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAA;KAAE,EAAE,CAAA;IAC5D,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAA;CAC3B;AAED,+EAA+E;AAC/E,wBAAgB,iBAAiB,IAAI,MAAM,CAE1C;AAED,0EAA0E;AAC1E,wBAAgB,aAAa,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM,CAKvD;AAED,wBAAgB,oBAAoB,CAAC,SAAS,EAAE,MAAM,EAAE,GAAG,GAAE,MAA4B,GAAG,MAAM,CAEjG;AAED;;;;GAIG;AACH,wBAAgB,uBAAuB,CACrC,SAAS,EAAE,MAAM,EACjB,GAAG,GAAE,MAA4B,GAChC,MAAM,CAER;AAED;;;;GAIG;AACH,wBAAgB,kBAAkB,CAChC,SAAS,EAAE,MAAM,GAAG,SAAS,EAC7B,GAAG,GAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,CAAe,EAC/D,GAAG,GAAE,MAA4B,GAChC,MAAM,GAAG,SAAS,CAMpB;AAuBD;;;;GAIG;AACH,wBA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AAE,MAAM,GAAG,SAAS,EAC7B,GAAG,GAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,CAAe,EAC/D,GAAG,GAAE,MAA4B,GAChC,MAAM,GAAG,SAAS,CAMpB;AAeD,4EAA4E;AAC5E,wBAAgB,cAAc,CAAC,OAAO,EAAE,WAAW,GAAG,MAAM,CAE3D;AAED;;;GAGG;AACH,wBAAgB,YAAY,CAAC,GAAG,GAAE,MAA4B,GAAG,SAAS,WAAW,EAAE,CAEtF;AAoCD;;;;GAIG;AACH,wBAAgB,cAAc,CAC5B,QAAQ,EAAE,SAAS,WAAW,EAAE,EAChC,GAAG,GAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,CAAe,GAC9D,WAAW,GAAG,IAAI,CAYpB;AAED;;;;GAIG;AACH,wBAAgB,aAAa,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,WAAW,CAUlE;AAED,wBAAgB,WAAW,CACzB,SAAS,CAAC,EAAE,MAAM,EAClB,GAAG,GAAE,MAA4B,GAChC,WAAW,GAAG,IAAI,CASpB;AAED,wBAAgB,WAAW,CAAC,OAAO,EAAE,WAAW,EAAE,GAAG,GAAE,MAA4B,GAAG,MAAM,CAK3F;AAED,+EAA+E;AAC/E,wBAAgB,YAAY,CAC1B,SAAS,EAAE,MAAM,EACjB,GAAG,GAAE,MAA4B,EACjC,GAAG,GAAE,MAAmB,GACvB,IAAI,CAQN;AAED,wBAAgB,YAAY,CAAC,SAAS,EAAE,MAAM,EAAE,GAAG,GAAE,MAA4B,GAAG,OAAO,CAK1F"}
@@ -8,6 +8,7 @@
8
8
  import * as fs from 'node:fs';
9
9
  import * as os from 'node:os';
10
10
  import * as path from 'node:path';
11
+ import { normalizeHubAddress } from './hub-address.js';
11
12
  /** Where the cache lives; injectable so a test never touches the real home. */
12
13
  export function defaultSessionDir() {
13
14
  return path.join(os.homedir(), '.camstack');
@@ -54,17 +55,65 @@ function resolveSessionFile(serverUrl, dir) {
54
55
  const p = sessionFileForServer(serverUrl, dir);
55
56
  return fs.existsSync(p) ? p : null;
56
57
  }
58
+ return defaultSessionFile(dir);
59
+ }
60
+ /** When a session was last used: `lastUsedAt`, else when it was created. */
61
+ export function sessionRecency(session) {
62
+ return session.lastUsedAt ?? session.createdAt;
63
+ }
64
+ /**
65
+ * Every readable saved session, most recently used first (ties: file mtime).
66
+ * A corrupt or partial file is skipped, never fatal.
67
+ */
68
+ export function listSessions(dir = defaultSessionDir()) {
69
+ return listSessionEntries(dir).map((e) => e.session);
70
+ }
71
+ function listSessionEntries(dir) {
57
72
  if (!fs.existsSync(dir))
58
- return null;
59
- const files = fs
60
- .readdirSync(dir)
61
- .filter((f) => f.endsWith('.json'))
62
- .map((f) => path.join(dir, f));
63
- if (files.length === 0)
64
- return null;
65
- return files
66
- .map((f) => ({ f, mtime: fs.statSync(f).mtimeMs }))
67
- .toSorted((a, b) => b.mtime - a.mtime)[0].f;
73
+ return [];
74
+ const entries = [];
75
+ for (const name of fs.readdirSync(dir)) {
76
+ if (!name.endsWith('.json'))
77
+ continue;
78
+ const file = path.join(dir, name);
79
+ try {
80
+ const parsed = JSON.parse(fs.readFileSync(file, 'utf8'));
81
+ if (isSessionFile(parsed)) {
82
+ entries.push({
83
+ file,
84
+ session: parsed,
85
+ mtime: fs.statSync(file).mtimeMs,
86
+ });
87
+ }
88
+ }
89
+ catch {
90
+ // an unreadable file is not a session
91
+ }
92
+ }
93
+ return entries.toSorted((a, b) => sessionRecency(b.session) - sessionRecency(a.session) || b.mtime - a.mtime);
94
+ }
95
+ function defaultSessionFile(dir) {
96
+ return listSessionEntries(dir)[0]?.file ?? null;
97
+ }
98
+ /**
99
+ * THE default-session rule, used by every command that is given no server:
100
+ * 1. the session of `$CAMSTACK_SERVER`, when one is set and saved;
101
+ * 2. otherwise the most recently used session (`lastUsedAt`, else `createdAt`).
102
+ */
103
+ export function defaultSession(sessions, env = process.env) {
104
+ const named = env['CAMSTACK_SERVER']?.trim();
105
+ if (named) {
106
+ try {
107
+ const server = normalizeHubAddress(named);
108
+ const hit = sessions.find((s) => s.server === server);
109
+ if (hit)
110
+ return hit;
111
+ }
112
+ catch {
113
+ // a malformed $CAMSTACK_SERVER is reported by the command that resolves it
114
+ }
115
+ }
116
+ return sessions.toSorted((a, b) => sessionRecency(b) - sessionRecency(a))[0] ?? null;
68
117
  }
69
118
  /**
70
119
  * Shape check for a cached session blob. A partial or corrupted cache file
@@ -108,6 +157,18 @@ export function saveSession(session, dir = defaultSessionDir()) {
108
157
  fs.writeFileSync(file, JSON.stringify(session, null, 2), { mode: 0o600 });
109
158
  return file;
110
159
  }
160
+ /** Record that a command just used this session; best effort, never throws. */
161
+ export function touchSession(serverUrl, dir = defaultSessionDir(), now = Date.now()) {
162
+ const session = loadSession(serverUrl, dir);
163
+ if (!session)
164
+ return;
165
+ try {
166
+ saveSession({ ...session, lastUsedAt: now }, dir);
167
+ }
168
+ catch {
169
+ // a read-only home must not fail the command that used the session
170
+ }
171
+ }
111
172
  export function clearSession(serverUrl, dir = defaultSessionDir()) {
112
173
  const file = sessionFileForServer(serverUrl, dir);
113
174
  if (!fs.existsSync(file))
@@ -0,0 +1,53 @@
1
+ /**
2
+ * Hub candidates shared by every client that looks for a hub (D838, D839): the
3
+ * CLI's `login` / `discover` and the agent's local UI. Candidates come from
4
+ * what the LAN announces over mDNS plus whatever the caller already knows
5
+ * (cached sessions for the CLI, the configured hub address for an agent); each
6
+ * is probed on its https port, unreachable ones are dropped, the rest are
7
+ * deduped by host:port with every source that named them kept.
8
+ */
9
+ import { type BrowseOptions, type MdnsHub } from './mdns-browse.js';
10
+ export declare const MDNS_SOURCE_LABEL = "LAN (mDNS)";
11
+ /** One reachable hub and everything that said so. */
12
+ export interface HubCandidate {
13
+ /** `https://host:port`, the dedupe key's origin. */
14
+ readonly url: string;
15
+ readonly host: string;
16
+ readonly port: number;
17
+ readonly nodeId: string | null;
18
+ readonly version: string | null;
19
+ /** Human labels: "LAN (mDNS)", "saved session admin", "CAMSTACK_HUB_URL"… */
20
+ readonly sources: readonly string[];
21
+ }
22
+ /** A hub some source named, before it is probed. */
23
+ export interface RawCandidate {
24
+ readonly url: string;
25
+ readonly source: string;
26
+ readonly nodeId?: string | null;
27
+ readonly version?: string | null;
28
+ }
29
+ export interface DiscoverHubsDeps {
30
+ /** Hubs the caller already knows, each tagged with where it learned it. */
31
+ readonly known?: readonly RawCandidate[];
32
+ readonly browse?: (options: BrowseOptions) => Promise<readonly MdnsHub[]>;
33
+ readonly probe?: (host: string, port: number) => Promise<boolean>;
34
+ readonly mdnsTimeoutMs?: number;
35
+ readonly onProblem?: (message: string) => void;
36
+ }
37
+ /** `https://host:port` for any URL-ish string; null when it is not an http(s) URL. */
38
+ export declare function normalizeHubUrl(value: string): {
39
+ url: string;
40
+ host: string;
41
+ port: number;
42
+ } | null;
43
+ /** Merge raw candidates by host:port, keeping every source and any identity. */
44
+ export declare function mergeCandidates(raw: readonly RawCandidate[]): readonly HubCandidate[];
45
+ /** The hubs worth offering: announced or known, deduped, and answering on https. */
46
+ export declare function discoverHubs(deps?: DiscoverHubsDeps): Promise<readonly HubCandidate[]>;
47
+ /**
48
+ * HEAD probe with a short timeout. `rejectUnauthorized: false` is intentional —
49
+ * hubs serve a private-CA certificate and this only asks "is something
50
+ * answering https here"; no credential is ever sent.
51
+ */
52
+ export declare function probeHttps(host: string, port: number): Promise<boolean>;
53
+ //# sourceMappingURL=hub-candidates.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hub-candidates.d.ts","sourceRoot":"","sources":["../../src/hub-discovery/hub-candidates.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AACH,OAAO,EAAE,KAAK,aAAa,EAAkB,KAAK,OAAO,EAAE,MAAM,kBAAkB,CAAA;AAKnF,eAAO,MAAM,iBAAiB,eAAe,CAAA;AAE7C,qDAAqD;AACrD,MAAM,WAAW,YAAY;IAC3B,oDA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ED,gFAAgF;AAChF,wBAAgB,eAAe,CAAC,GAAG,EAAE,SAAS,YAAY,EAAE,GAAG,SAAS,YAAY,EAAE,CAmBrF;AAED,oFAAoF;AACpF,wBAAsB,YAAY,CAAC,IAAI,GAAE,gBAAqB,GAAG,OAAO,CAAC,SAAS,YAAY,EAAE,CAAC,CAmBhG;AAED;;;;GAIG;AACH,wBAAsB,UAAU,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAwB7E"}
@@ -0,0 +1,103 @@
1
+ /**
2
+ * Hub candidates shared by every client that looks for a hub (D838, D839): the
3
+ * CLI's `login` / `discover` and the agent's local UI. Candidates come from
4
+ * what the LAN announces over mDNS plus whatever the caller already knows
5
+ * (cached sessions for the CLI, the configured hub address for an agent); each
6
+ * is probed on its https port, unreachable ones are dropped, the rest are
7
+ * deduped by host:port with every source that named them kept.
8
+ */
9
+ import { browseHubsMdns } from './mdns-browse.js';
10
+ const DEFAULT_HTTPS_PORT = 443;
11
+ const PROBE_TIMEOUT_MS = 1500;
12
+ const DEFAULT_MDNS_TIMEOUT_MS = 3_000;
13
+ export const MDNS_SOURCE_LABEL = 'LAN (mDNS)';
14
+ /** `https://host:port` for any URL-ish string; null when it is not an http(s) URL. */
15
+ export function normalizeHubUrl(value) {
16
+ let parsed;
17
+ try {
18
+ parsed = new URL(value.trim());
19
+ }
20
+ catch {
21
+ return null;
22
+ }
23
+ if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:')
24
+ return null;
25
+ if (parsed.hostname === '')
26
+ return null;
27
+ const port = parsed.port === '' ? DEFAULT_HTTPS_PORT : Number.parseInt(parsed.port, 10);
28
+ // A hub is reached over https; an http URL is probed on its https sibling only
29
+ // when it names a port, so keep the host:port as written.
30
+ const host = parsed.hostname.replace(/^\[|\]$/g, '');
31
+ const shown = host.includes(':') ? `[${host}]` : host;
32
+ return { url: `https://${shown}:${port}`, host, port };
33
+ }
34
+ /** Merge raw candidates by host:port, keeping every source and any identity. */
35
+ export function mergeCandidates(raw) {
36
+ const merged = new Map();
37
+ for (const r of raw) {
38
+ const n = normalizeHubUrl(r.url);
39
+ if (n === null)
40
+ continue;
41
+ const key = `${n.host}:${n.port}`;
42
+ const prev = merged.get(key);
43
+ merged.set(key, {
44
+ url: n.url,
45
+ host: n.host,
46
+ port: n.port,
47
+ nodeId: prev?.nodeId ?? r.nodeId ?? null,
48
+ version: prev?.version ?? r.version ?? null,
49
+ sources: prev?.sources.includes(r.source)
50
+ ? prev.sources
51
+ : [...(prev?.sources ?? []), r.source],
52
+ });
53
+ }
54
+ return [...merged.values()];
55
+ }
56
+ /** The hubs worth offering: announced or known, deduped, and answering on https. */
57
+ export async function discoverHubs(deps = {}) {
58
+ const browse = deps.browse ?? browseHubsMdns;
59
+ const probe = deps.probe ?? probeHttps;
60
+ const announced = await browse({
61
+ timeoutMs: deps.mdnsTimeoutMs ?? DEFAULT_MDNS_TIMEOUT_MS,
62
+ ...(deps.onProblem ? { onProblem: deps.onProblem } : {}),
63
+ });
64
+ const raw = [
65
+ ...announced.map((h) => ({
66
+ url: h.url,
67
+ source: MDNS_SOURCE_LABEL,
68
+ nodeId: h.nodeId,
69
+ version: h.version,
70
+ })),
71
+ ...(deps.known ?? []),
72
+ ];
73
+ const candidates = mergeCandidates(raw);
74
+ const verdicts = await Promise.all(candidates.map((c) => probe(c.host, c.port)));
75
+ return candidates.filter((_, i) => verdicts[i] === true);
76
+ }
77
+ /**
78
+ * HEAD probe with a short timeout. `rejectUnauthorized: false` is intentional —
79
+ * hubs serve a private-CA certificate and this only asks "is something
80
+ * answering https here"; no credential is ever sent.
81
+ */
82
+ export async function probeHttps(host, port) {
83
+ const { request } = await import('node:https');
84
+ return new Promise((resolve) => {
85
+ const req = request({
86
+ host,
87
+ port,
88
+ method: 'HEAD',
89
+ path: '/trpc/health',
90
+ timeout: PROBE_TIMEOUT_MS,
91
+ rejectUnauthorized: false,
92
+ }, (res) => {
93
+ resolve(typeof res.statusCode === 'number');
94
+ res.resume();
95
+ });
96
+ req.on('error', () => resolve(false));
97
+ req.on('timeout', () => {
98
+ req.destroy();
99
+ resolve(false);
100
+ });
101
+ req.end();
102
+ });
103
+ }
@@ -0,0 +1,4 @@
1
+ /** Finding hubs on the LAN (D838) — shared by the CLI and the agent backend (D839). */
2
+ export { type DiscoverHubsDeps, discoverHubs, type HubCandidate, mergeCandidates, MDNS_SOURCE_LABEL, normalizeHubUrl, probeHttps, type RawCandidate, } from './hub-candidates.js';
3
+ export { type BrowseOptions, browseHubsMdns, createRealMdnsSocket, hubsFromResponses, type MdnsHub, type MdnsRecord, type MdnsResponse, type MdnsSocket, } from './mdns-browse.js';
4
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/hub-discovery/index.ts"],"names":[],"mappings":"AAAA,uFAAuF;AACvF,OAAO,EACL,KAAK,gBAAgB,EACrB,YAAY,EACZ,KAAK,YAAY,EACjB,eAAe,EACf,iBAAiB,EACjB,eAAe,EACf,UAAU,EACV,KAAK,YAAY,GAClB,MAAM,qBAAqB,CAAA;AAC5B,OAAO,EACL,KAAK,aAAa,EAClB,cAAc,EACd,oBAAoB,EACpB,iBAAiB,EACjB,KAAK,OAAO,EACZ,KAAK,UAAU,EACf,KAAK,YAAY,EACjB,KAAK,UAAU,GAChB,MAAM,kBAAkB,CAAA"}
@@ -0,0 +1,3 @@
1
+ /** Finding hubs on the LAN (D838) — shared by the CLI and the agent backend (D839). */
2
+ export { discoverHubs, mergeCandidates, MDNS_SOURCE_LABEL, normalizeHubUrl, probeHttps, } from './hub-candidates.js';
3
+ export { browseHubsMdns, createRealMdnsSocket, hubsFromResponses, } from './mdns-browse.js';
@@ -0,0 +1,51 @@
1
+ /** The records the browse cares about, free of the wire library's types. */
2
+ export type MdnsRecord = {
3
+ readonly kind: 'ptr';
4
+ readonly name: string;
5
+ readonly target: string;
6
+ } | {
7
+ readonly kind: 'srv';
8
+ readonly name: string;
9
+ readonly port: number;
10
+ readonly target: string;
11
+ } | {
12
+ readonly kind: 'txt';
13
+ readonly name: string;
14
+ readonly entries: readonly string[];
15
+ } | {
16
+ readonly kind: 'a';
17
+ readonly name: string;
18
+ readonly address: string;
19
+ };
20
+ /** One response packet: its records and the sender's address. */
21
+ export interface MdnsResponse {
22
+ readonly records: readonly MdnsRecord[];
23
+ readonly from: string;
24
+ }
25
+ /** The mDNS socket seam; a fake implements it in specs. */
26
+ export interface MdnsSocket {
27
+ onResponse(listener: (response: MdnsResponse) => void): void;
28
+ onError(listener: (error: Error) => void): void;
29
+ query(name: string): void;
30
+ destroy(): void;
31
+ }
32
+ export interface MdnsHub {
33
+ /** Base https URL, no trailing slash. */
34
+ readonly url: string;
35
+ readonly nodeId: string | null;
36
+ readonly version: string | null;
37
+ }
38
+ export interface BrowseOptions {
39
+ readonly timeoutMs: number;
40
+ readonly createSocket?: () => MdnsSocket;
41
+ /** Re-ask this often so a hub that missed the first question answers. */
42
+ readonly requeryMs?: number;
43
+ /** Told why the browse found nothing when the multicast stack failed. */
44
+ readonly onProblem?: (message: string) => void;
45
+ }
46
+ export declare function createRealMdnsSocket(): MdnsSocket;
47
+ /** Fold the responses into hubs. Pure, so it is tested without sockets. */
48
+ export declare function hubsFromResponses(responses: readonly MdnsResponse[]): readonly MdnsHub[];
49
+ /** Listen for `_camstack._tcp` for `timeoutMs`; never throws (no multicast = no hubs). */
50
+ export declare function browseHubsMdns(options: BrowseOptions): Promise<readonly MdnsHub[]>;
51
+ //# sourceMappingURL=mdns-browse.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mdns-browse.d.ts","sourceRoot":"","sources":["../../src/hub-discovery/mdns-browse.ts"],"names":[],"mappings":"AASA,4EAA4E;AAC5E,MAAM,MAAM,UAAU,GAClB;IAAE,QAAQ,CAAC,IAAI,EAAE,KAAK,CAAC;IAAC,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IAA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,MAAM,CAAA;IAC1B,QAAQ,CAAC,YAAY,CAAC,EAAE,MAAM,UAAU,CAAA;IACxC,yEAAyE;IACzE,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,CAAA;IAC3B,yEAAyE;IACzE,QAAQ,CAAC,SAAS,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,IAAI,CAAA;CAC/C;AAED,wBAAgB,oBAAoB,IAAI,UAAU,CAyBjD;AAqBD,2EAA2E;AAC3E,wBAAgB,iBAAiB,CAAC,SAAS,EAAE,SAAS,YAAY,EAAE,GAAG,SAAS,OAAO,EAAE,CA0BxF;AAED,0FAA0F;AAC1F,wBAAsB,cAAc,CAAC,OAAO,EAAE,aAAa,GAAG,OAAO,CAAC,SAAS,OAAO,EAAE,CAAC,CAyBxF"}
@@ -0,0 +1,116 @@
1
+ /**
2
+ * Browse the LAN for hubs over mDNS (D838): the hub publishes ONE
3
+ * `_camstack._tcp` service for its HTTPS endpoint. This module only listens
4
+ * for that service — it never reads the mesh multicast channel (D826 retired
5
+ * it on the hub, so it can only ever show pre-D826 hubs).
6
+ */
7
+ import { HUB_MDNS_QUERY_NAME, HUB_MDNS_ROLE, HUB_MDNS_TXT_KEYS } from '@camstack/types';
8
+ import makeMdns from 'multicast-dns';
9
+ export function createRealMdnsSocket() {
10
+ const socket = makeMdns();
11
+ return {
12
+ onResponse: (listener) => {
13
+ socket.on('response', (packet, rinfo) => {
14
+ const records = [];
15
+ for (const a of [...packet.answers, ...packet.additionals]) {
16
+ if (a.type === 'PTR')
17
+ records.push({ kind: 'ptr', name: a.name, target: a.data });
18
+ else if (a.type === 'A')
19
+ records.push({ kind: 'a', name: a.name, address: a.data });
20
+ else if (a.type === 'SRV')
21
+ records.push({ kind: 'srv', name: a.name, port: a.data.port, target: a.data.target });
22
+ else if (a.type === 'TXT') {
23
+ const raw = Array.isArray(a.data) ? a.data : [a.data];
24
+ records.push({ kind: 'txt', name: a.name, entries: raw.map((e) => e.toString()) });
25
+ }
26
+ }
27
+ listener({ records, from: rinfo.address });
28
+ });
29
+ },
30
+ onError: (listener) => {
31
+ socket.on('error', listener);
32
+ },
33
+ query: (name) => socket.query({ questions: [{ name, type: 'PTR' }] }),
34
+ destroy: () => socket.destroy(),
35
+ };
36
+ }
37
+ function parseTxt(entries) {
38
+ const out = new Map();
39
+ for (const entry of entries) {
40
+ const at = entry.indexOf('=');
41
+ if (at > 0)
42
+ out.set(entry.slice(0, at), entry.slice(at + 1));
43
+ }
44
+ return out;
45
+ }
46
+ function originOf(value) {
47
+ if (value === undefined)
48
+ return null;
49
+ try {
50
+ const u = new URL(value);
51
+ return u.protocol === 'https:' ? u.origin : null;
52
+ }
53
+ catch {
54
+ return null;
55
+ }
56
+ }
57
+ /** Fold the responses into hubs. Pure, so it is tested without sockets. */
58
+ export function hubsFromResponses(responses) {
59
+ const found = new Map();
60
+ for (const { records, from } of responses) {
61
+ for (const ptr of records) {
62
+ if (ptr.kind !== 'ptr')
63
+ continue;
64
+ const srv = records.find((r) => r.kind === 'srv' && r.name === ptr.target);
65
+ if (srv?.kind !== 'srv')
66
+ continue;
67
+ const txtRecord = records.find((r) => r.kind === 'txt' && r.name === ptr.target);
68
+ const txt = txtRecord?.kind === 'txt' ? parseTxt(txtRecord.entries) : new Map();
69
+ // A service that is not a hub is not ours to list.
70
+ const role = txt.get(HUB_MDNS_TXT_KEYS.role);
71
+ if (role !== undefined && role !== HUB_MDNS_ROLE)
72
+ continue;
73
+ const a = records.find((r) => r.kind === 'a' && r.name === srv.target);
74
+ const host = a?.kind === 'a' ? a.address : from;
75
+ // The advertised URL is the hub's own answer (its `internal` address);
76
+ // the A record and the packet's source are the fallback.
77
+ const url = originOf(txt.get(HUB_MDNS_TXT_KEYS.url)) ?? `https://${host}:${srv.port}`;
78
+ found.set(url, {
79
+ url,
80
+ nodeId: txt.get(HUB_MDNS_TXT_KEYS.nodeId) ?? null,
81
+ version: txt.get(HUB_MDNS_TXT_KEYS.version) ?? null,
82
+ });
83
+ }
84
+ }
85
+ return [...found.values()];
86
+ }
87
+ /** Listen for `_camstack._tcp` for `timeoutMs`; never throws (no multicast = no hubs). */
88
+ export async function browseHubsMdns(options) {
89
+ const responses = [];
90
+ const problem = (error) => options.onProblem?.(error instanceof Error ? error.message : String(error));
91
+ let socket;
92
+ try {
93
+ socket = (options.createSocket ?? createRealMdnsSocket)();
94
+ }
95
+ catch (err) {
96
+ problem(err);
97
+ return [];
98
+ }
99
+ let requery = null;
100
+ try {
101
+ socket.onResponse((r) => responses.push(r));
102
+ socket.onError(problem);
103
+ socket.query(HUB_MDNS_QUERY_NAME);
104
+ requery = setInterval(() => socket.query(HUB_MDNS_QUERY_NAME), options.requeryMs ?? 1000);
105
+ await new Promise((resolve) => setTimeout(resolve, options.timeoutMs));
106
+ }
107
+ catch (err) {
108
+ problem(err);
109
+ }
110
+ finally {
111
+ if (requery !== null)
112
+ clearInterval(requery);
113
+ socket.destroy();
114
+ }
115
+ return hubsFromResponses(responses);
116
+ }
package/dist/index.d.ts CHANGED
@@ -14,10 +14,11 @@ export { extendAddon } from './scaffold/extend.js';
14
14
  export { listSkills, readSkill, resolveSkillsDir } from './skills.js';
15
15
  export { ADMIN_TOKEN_PREFIX, authRejectedHint, credentialTier, MissingCredentialsError, readTokenFile, resolveCredentials, withAuthHint, } from './hub/credentials.js';
16
16
  export type { CachedSessionLike, CredentialInputs, CredentialSource, CredentialTier, ResolvedCredentials, TokenFileContents, } from './hub/credentials.js';
17
- export { adminTokenFileForServer, clearSession, defaultSessionDir, findAdminTokenFile, isSessionFile, loadSession, saveSession, sessionFileForServer, slugForServer, } from './hub/session-store.js';
17
+ export { adminTokenFileForServer, clearSession, defaultSession, defaultSessionDir, findAdminTokenFile, isSessionFile, listSessions, loadSession, saveSession, sessionFileForServer, sessionRecency, slugForServer, touchSession, } from './hub/session-store.js';
18
18
  export type { SessionFile } from './hub/session-store.js';
19
19
  export { adminCredentialHint, adminLoginCommand, adminRejectedHint, adminTokenMetaFileForServer, adminTokenStatus, readPreviousAdminToken, REPO_LOCAL_LOGIN_ADMIN, saveAdminToken, } from './hub/admin-token-store.js';
20
20
  export type { AdminTokenMeta, AdminTokenStatus, PreviousAdminToken, } from './hub/admin-token-store.js';
21
+ export { DEFAULT_HUB_PORT, HubAddressError, normalizeHubAddress, validateHubAddress, } from './hub/hub-address.js';
21
22
  export { resolveHubUrl } from './hub/hub-url.js';
22
23
  export type { HubUrlInputs, HubUrlSource, ResolvedHubUrl, } from './hub/hub-url.js';
23
24
  export { createHubAgent, explainTlsFailure, hubCaFileForServer, resolveHubTls, } from './hub/hub-tls.js';
@@ -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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,EAChB,aAAa,EACb,YAAY,EACZ,mBAAmB,EACnB,oBAAoB,GACrB,MAAM,qBAAqB,CAAA"}
package/dist/index.js CHANGED
@@ -14,8 +14,9 @@ export { listSkills, readSkill, resolveSkillsDir } from './skills.js';
14
14
  // Hub access — the one credential chain, session cache, address and TLS trust
15
15
  // shared by the CLI, scripts/hub/hub.mjs and the operator MCP (D835).
16
16
  export { ADMIN_TOKEN_PREFIX, authRejectedHint, credentialTier, MissingCredentialsError, readTokenFile, resolveCredentials, withAuthHint, } from './hub/credentials.js';
17
- export { adminTokenFileForServer, clearSession, defaultSessionDir, findAdminTokenFile, isSessionFile, loadSession, saveSession, sessionFileForServer, slugForServer, } from './hub/session-store.js';
17
+ export { adminTokenFileForServer, clearSession, defaultSession, defaultSessionDir, findAdminTokenFile, isSessionFile, listSessions, loadSession, saveSession, sessionFileForServer, sessionRecency, slugForServer, touchSession, } from './hub/session-store.js';
18
18
  export { adminCredentialHint, adminLoginCommand, adminRejectedHint, adminTokenMetaFileForServer, adminTokenStatus, readPreviousAdminToken, REPO_LOCAL_LOGIN_ADMIN, saveAdminToken, } from './hub/admin-token-store.js';
19
+ export { DEFAULT_HUB_PORT, HubAddressError, normalizeHubAddress, validateHubAddress, } from './hub/hub-address.js';
19
20
  export { resolveHubUrl } from './hub/hub-url.js';
20
21
  export { createHubAgent, explainTlsFailure, hubCaFileForServer, resolveHubTls, } from './hub/hub-tls.js';
21
22
  export { createHubClient, encodeTrpcInput, HubHttpError, HubRpcError, nodeHubTransport, } from './hub/hub-client.js';
@@ -1 +1 @@
1
- {"version":3,"file":"skills.d.ts","sourceRoot":"","sources":["../src/skills.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,YAAY,CAAA;AAI3C,wBAAgB,gBAAgB,IAAI,MAAM,CAMzC;AA4BD,wBAAgB,UAAU,IAAI,SAAS,SAAS,EAAE,CAQjD;AAED,wBAAgB,SAAS,CAAC,EAAE,EAAE,MAAM,GAAG;IAAE,IAAI,EAAE,SAAS,CAAC;IAAC,OAAO,EAAE,MAAM,CAAA;CAAE,GAAG,IAAI,CAMjF"}
1
+ {"version":3,"file":"skills.d.ts","sourceRoot":"","sources":["../src/skills.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,YAAY,CAAA;AAI3C,wBAAgB,gBAAgB,IAAI,MAAM,CAMzC;AAiCD,wBAAgB,UAAU,IAAI,SAAS,SAAS,EAAE,CAQjD;AAED,wBAAgB,SAAS,CAAC,EAAE,EAAE,MAAM,GAAG;IAAE,IAAI,EAAE,SAAS,CAAC;IAAC,OAAO,EAAE,MAAM,CAAA;CAAE,GAAG,IAAI,CAMjF"}
package/dist/skills.js CHANGED
@@ -24,6 +24,11 @@ const SKILL_FILES = [
24
24
  file: 'architecture.md',
25
25
  title: 'Architecture pointers for plugin authors',
26
26
  },
27
+ {
28
+ id: 'track-review',
29
+ file: 'track-review.md',
30
+ title: 'Review wrong-class tracks and curate the re-training set',
31
+ },
27
32
  ];
28
33
  /**
29
34
  * The ids before the 2026-10-09 rename to the server repository's skill names.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@camstack/develop",
3
- "version": "0.1.4",
3
+ "version": "0.1.6",
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",
@@ -22,6 +22,10 @@
22
22
  "types": "./dist/index.d.ts",
23
23
  "import": "./dist/index.js"
24
24
  },
25
+ "./hub-discovery": {
26
+ "types": "./dist/hub-discovery/index.d.ts",
27
+ "import": "./dist/hub-discovery/index.js"
28
+ },
25
29
  "./package.json": "./package.json"
26
30
  },
27
31
  "files": [
@@ -37,8 +41,13 @@
37
41
  "node": ">=24"
38
42
  },
39
43
  "devDependencies": {
44
+ "@types/multicast-dns": "^7.2.4",
40
45
  "@types/node": "^24",
41
46
  "typescript": "~6.0.3",
42
47
  "vitest": "^3.0.0"
48
+ },
49
+ "dependencies": {
50
+ "@camstack/types": "*",
51
+ "multicast-dns": "^7.2.5"
43
52
  }
44
53
  }
package/skills/README.md CHANGED
@@ -11,6 +11,7 @@ third-party use (no private hostnames, no hub-specific ops).
11
11
  | `camstack-secrets` | [camstack-secrets.md](./camstack-secrets.md) | Password / token / key fields |
12
12
  | `camstack-docs` | [camstack-docs.md](./camstack-docs.md) | Generated vs prose docs |
13
13
  | `architecture` | [architecture.md](./architecture.md) | Plugin-author architecture pointers |
14
+ | `track-review` | [track-review.md](./track-review.md) | Find wrong-class tracks, curate the re-training set (`track_review_*` MCP tools) |
14
15
 
15
16
  These files are the canonical public text. In the server repository the
16
17
  matching `.claude/skills/<id>/SKILL.md` is an overlay that points here and keeps
@@ -42,7 +43,9 @@ npx @camstack/mcp-develop
42
43
  ```
43
44
 
44
45
  Tools wrap the same `@camstack/develop` operations (`list_addons`,
45
- `scaffold_addon`, `validate_addon`, `find_example`, `get_skill`, …).
46
+ `scaffold_addon`, `validate_addon`, `find_example`, `get_skill`, …). The
47
+ `track_review_*` tools additionally talk to a hub — see the `track-review` skill
48
+ for the environment variables and the confirm-before-write rule.
46
49
 
47
50
  ### Agents
48
51
 
@@ -0,0 +1,130 @@
1
+ ---
2
+ name: track-review
3
+ description: Review recent tracks for a wrong class and curate the corrected frames into the re-training set — triage suspects, look at each, give a verdict, show the operator the write list, then apply it. Use for "find tracks the detector got wrong", "this animal is labelled as the wrong species", "build a retrain collection from recent mistakes", or when setting up the `track_review_*` MCP tools.
4
+ ---
5
+
6
+ # Track review
7
+
8
+ A detector's mistakes are the most valuable training data it will ever get, and
9
+ they hide inside thousands of correct tracks. This procedure finds the likely
10
+ mistakes, has a model (and then the operator) look at them, and writes only the
11
+ confirmed ones into the re-training set with the right boxes.
12
+
13
+ It is the MCP tools `track_review_triage`, `track_review_frame`,
14
+ `track_review_plan`, `track_review_apply` of `@camstack/mcp-develop`. Without the
15
+ MCP, the same hub methods can be called by hand; the order below still holds.
16
+
17
+ ## 0. Configure the MCP
18
+
19
+ The server reads three environment variables. Nothing else, no flags.
20
+
21
+ | Variable | Meaning |
22
+ | --- | --- |
23
+ | `CAMSTACK_HUB_URL` | Hub address (`https://hub.local:4443`; a bare host is completed to the default port). |
24
+ | `CAMSTACK_HUB_TOKEN_FILE` | Path to a file holding ONE token, mode 0600 (preferred). `CAMSTACK_HUB_TOKEN` also works but leaks into process listings. |
25
+ | `CAMSTACK_HUB_CA_FILE` | PEM of the hub's CA or pinned certificate, for a self-signed hub. |
26
+
27
+ TLS verification is never turned off: a certificate error is fixed by naming the
28
+ CA, not by disabling the check. Triage and frame need a normal token;
29
+ **apply needs an admin token** and shows the hub's own refusal if the token
30
+ lacks it. Tokens are never printed.
31
+
32
+ ```json
33
+ { "mcpServers": { "camstack-develop": {
34
+ "command": "npx", "args": ["@camstack/mcp-develop"],
35
+ "env": { "CAMSTACK_HUB_URL": "https://hub.local:4443",
36
+ "CAMSTACK_HUB_TOKEN_FILE": "/home/me/.camstack/review.token",
37
+ "CAMSTACK_HUB_CA_FILE": "/home/me/.camstack/hub-ca.pem" } } } }
38
+ ```
39
+
40
+ ## 1. Triage — rank, do not judge
41
+
42
+ `track_review_triage { hours, deviceIds?, classes? }` pages the window (default
43
+ 72 h, at most 14 days), scores every video track, and returns the top suspects
44
+ with their features, plus a **random control sample** of tracks that scored low.
45
+
46
+ The score is a sum of cheap signals. None of them says "wrong"; together they say
47
+ "look here first":
48
+
49
+ | Signal | Why it matters | Known failure mode of the signal |
50
+ | --- | --- | --- |
51
+ | `class-label-mismatch` | the sub-label belongs to a different macro class than the track's class | rare; a real reclassification, not noise |
52
+ | `suspect-label` | a label small or unusual subjects are commonly mistaken for (cat, bird, teddy bear, sheep) | fires on every genuine one too; read it with the score |
53
+ | `low-label-score` | weak classification confidence | weak is not wrong; a good label can score low in the dark |
54
+ | `very-short` / `few-observations` | seen for a moment, often a mis-detection or an edge | a fast mover is also short |
55
+ | `tiny-subject` | the trajectory box is a sliver of the frame | a distant subject is legitimately tiny |
56
+ | `static-subject` | a person or vehicle that never moved: the profile of a picture of one | a person sitting still is real |
57
+ | `class-changed` | the track was reclassified during its life | usually the fix working |
58
+
59
+ Confusions worth looking for on purpose, because they repeat:
60
+
61
+ - a small, light-coloured dog read as a cat or a bird, worst when it is far away;
62
+ - vehicles and people on a **television or monitor** (they appear, never leave
63
+ the screen, and the same programme repeats);
64
+ - a person read as another class when partly hidden or lying down, and the
65
+ reverse: a coat, a plant or a shadow read as a person;
66
+ - the same subject split into two tracks with different classes.
67
+
68
+ Raise or lower `minScore`, pass `suspectLabels`, or restrict `classes` to chase
69
+ one confusion. If `fetched.truncated` is true the window was cut by the page
70
+ cap: narrow it.
71
+
72
+ ## 2. Look at each suspect
73
+
74
+ `track_review_frame { deviceId, trackId }` returns a clean frame as an image
75
+ (bounded in size) with the features and the trajectory envelope. Judge the
76
+ subject in the picture, not the label. If the frame is missing or too small to
77
+ tell, the verdict is `unsure`.
78
+
79
+ ## 3. Verdicts
80
+
81
+ | Verdict | Meaning | Written? |
82
+ | --- | --- | --- |
83
+ | `correct` | the class is right | no |
84
+ | `wrong-class` | the subject is something else; say what (`correctClass`) | yes |
85
+ | `false-positive` | nothing is there; the model drew a box on a picture, a shadow, a reflection | yes, as a `model_error` box |
86
+ | `pipeline-bug` | the class is fine but the track is broken (split, merged, no media) | no — report it |
87
+ | `unsure` | cannot tell from the evidence | no — never train on a guess |
88
+
89
+ **Annotate every subject in the frame.** A frame is evaluated as ground truth: a
90
+ subject left unboxed counts against the detector as a false alarm. So when
91
+ reviewing a wrong-class track, box the other people and animals in the same
92
+ frame too (`subjects`), and set `complete: true` only when every subject is
93
+ boxed. A frame not marked complete is kept but stays out of detector evaluation;
94
+ that is the safe default.
95
+
96
+ ## 4. Check the misses: the control sample
97
+
98
+ The control sample is what keeps the signals honest. Review it exactly like the
99
+ suspects. If more than a handful of the control tracks turn out wrong, the
100
+ signals are missing a whole kind of mistake: say so, widen the net (lower
101
+ `minScore`, add `suspectLabels`) and rerun before trusting the suspect list. The
102
+ share of wrong tracks in the control sample is the miss rate — report it
103
+ alongside the findings.
104
+
105
+ ## 5. Plan, show, then apply
106
+
107
+ 1. `track_review_plan { verdicts }` — local, writes nothing. It returns, per
108
+ track, the steps (flag for training → copy the frame → save the corrected
109
+ boxes → mark complete → add to the collection), the subjects, and the
110
+ verdicts that write nothing with their reason.
111
+ 2. **Present that write list to the operator and wait.** Name the tracks, the
112
+ classes you will write, the collection, and how many frames will be marked
113
+ complete. This is the only moment to catch a wrong call cheaply.
114
+ 3. `track_review_apply { plan, collectionName, confirm: true }` — only after the
115
+ operator agrees. It refuses without `confirm: true` and an explicit
116
+ collection name.
117
+
118
+ Apply is safe to repeat: a frame already copied is reused, a frame that already
119
+ has annotations is left alone (`overwrite: true` replaces them — a save replaces
120
+ EVERY annotation on the frame), the collection is created once, a track that
121
+ fails does not stop the others, and an authorisation failure stops the run and
122
+ shows the hub's message. It returns a per-track log and the corpus KPI
123
+ (total / annotated / complete frames) before and after; quote both.
124
+
125
+ ## Done when
126
+
127
+ - every suspect and every control track has a verdict;
128
+ - the operator saw the write list before apply;
129
+ - the per-track log shows each planned track `done`, or the reason it did not;
130
+ - the KPI moved by what was planned and the control-sample miss rate is reported.