@skrr-ai/cli 0.1.142 → 0.1.144

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (156) hide show
  1. package/README.md +8 -0
  2. package/dist/base-command.d.ts +4 -2
  3. package/dist/base-command.js +46 -13
  4. package/dist/commands/agenda/trigger/create.js +4 -2
  5. package/dist/commands/agenda/trigger/list.js +7 -7
  6. package/dist/commands/agent/message/approve.d.ts +17 -0
  7. package/dist/commands/agent/message/approve.js +72 -0
  8. package/dist/commands/agent/message/decline.d.ts +17 -0
  9. package/dist/commands/agent/message/decline.js +72 -0
  10. package/dist/commands/agent/message/pending.d.ts +18 -0
  11. package/dist/commands/agent/message/pending.js +79 -0
  12. package/dist/commands/agents/always-on/disable.js +9 -1
  13. package/dist/commands/agents/always-on/enable.js +9 -1
  14. package/dist/commands/agents/always-on/status.js +14 -1
  15. package/dist/commands/agents/create.js +10 -1
  16. package/dist/commands/agents/delete.d.ts +51 -0
  17. package/dist/commands/agents/delete.js +163 -2
  18. package/dist/commands/agents/intuitions/list.js +1 -1
  19. package/dist/commands/agents/plan-day.d.ts +39 -7
  20. package/dist/commands/agents/plan-day.js +254 -65
  21. package/dist/commands/agents/proactive-audit.d.ts +22 -0
  22. package/dist/commands/agents/proactive-audit.js +86 -0
  23. package/dist/commands/agents/schedule-overview.d.ts +7 -0
  24. package/dist/commands/agents/schedule-overview.js +43 -5
  25. package/dist/commands/agents/schedule-trace.js +30 -19
  26. package/dist/commands/agents/spawn.d.ts +51 -0
  27. package/dist/commands/agents/spawn.js +212 -9
  28. package/dist/commands/agents/todos/cancel.js +3 -0
  29. package/dist/commands/agents/todos/edit.js +1 -1
  30. package/dist/commands/agents/todos/list.d.ts +5 -0
  31. package/dist/commands/agents/todos/list.js +19 -5
  32. package/dist/commands/agents/triggers/create.js +1 -1
  33. package/dist/commands/agents/triggers/policy.js +7 -0
  34. package/dist/commands/agents/triggers/update.js +1 -1
  35. package/dist/commands/commitments/create.js +13 -3
  36. package/dist/commands/commitments/preflight.js +31 -5
  37. package/dist/commands/daemon/index.js +1 -0
  38. package/dist/commands/daemon/logs.d.ts +8 -1
  39. package/dist/commands/daemon/logs.js +32 -22
  40. package/dist/commands/daemon/profile.d.ts +15 -0
  41. package/dist/commands/daemon/profile.js +51 -0
  42. package/dist/commands/goals/briefing/status.js +1 -1
  43. package/dist/commands/initiatives/worker/deactivate.d.ts +23 -0
  44. package/dist/commands/initiatives/worker/deactivate.js +78 -0
  45. package/dist/commands/login.js +8 -2
  46. package/dist/commands/logout.d.ts +20 -0
  47. package/dist/commands/logout.js +110 -5
  48. package/dist/commands/machines/profiles/disconnect.d.ts +23 -0
  49. package/dist/commands/machines/profiles/disconnect.js +102 -0
  50. package/dist/commands/machines/profiles/index.d.ts +15 -0
  51. package/dist/commands/machines/profiles/index.js +33 -0
  52. package/dist/commands/machines/profiles/label.d.ts +24 -0
  53. package/dist/commands/machines/profiles/label.js +85 -0
  54. package/dist/commands/machines/profiles/list.d.ts +16 -0
  55. package/dist/commands/machines/profiles/list.js +87 -0
  56. package/dist/commands/memory/maintain.js +16 -2
  57. package/dist/commands/profiles/list.js +17 -2
  58. package/dist/commands/spaces/delete.js +6 -1
  59. package/dist/commands/spaces/workflows/archive.js +6 -1
  60. package/dist/commands/spaces/workflows/publish.js +3 -1
  61. package/dist/commands/spaces/workflows/run.d.ts +1 -0
  62. package/dist/commands/spaces/workflows/run.js +17 -1
  63. package/dist/commands/spaces/workflows/triggers/create.js +3 -1
  64. package/dist/commands/tasks/workflow-context.js +3 -1
  65. package/dist/commands/triggers/authorization.js +1 -1
  66. package/dist/commands/triggers/capabilities.js +17 -1
  67. package/dist/commands/triggers/create.d.ts +2 -0
  68. package/dist/commands/triggers/create.js +23 -7
  69. package/dist/commands/triggers/fire-detail.js +12 -3
  70. package/dist/commands/triggers/list.d.ts +1 -0
  71. package/dist/commands/triggers/list.js +13 -1
  72. package/dist/commands/triggers/preflight.js +18 -0
  73. package/dist/commands/triggers/prune.js +9 -5
  74. package/dist/commands/triggers/update.js +13 -4
  75. package/dist/generated/agent-guides.json +35 -35
  76. package/dist/lib/agent-guides.js +1 -1
  77. package/dist/lib/agent-proactive-baseline.d.ts +6 -0
  78. package/dist/lib/agent-proactive-baseline.js +32 -3
  79. package/dist/lib/always-on-command-result.d.ts +18 -0
  80. package/dist/lib/always-on-command-result.js +52 -0
  81. package/dist/lib/always-on-runtime.d.ts +31 -0
  82. package/dist/lib/always-on-runtime.js +39 -0
  83. package/dist/lib/auth-diagnostics.d.ts +10 -1
  84. package/dist/lib/auth-diagnostics.js +16 -8
  85. package/dist/lib/commitments.d.ts +16 -9
  86. package/dist/lib/commitments.js +65 -4
  87. package/dist/lib/compasses.js +5 -0
  88. package/dist/lib/daemon-binding.js +6 -3
  89. package/dist/lib/daemon-command-hint.d.ts +10 -5
  90. package/dist/lib/daemon-command-hint.js +11 -6
  91. package/dist/lib/daemon-setup.js +9 -3
  92. package/dist/lib/daemonBroker.d.ts +7 -0
  93. package/dist/lib/daemonBroker.js +5 -0
  94. package/dist/lib/daemonHandoff.d.ts +2 -0
  95. package/dist/lib/daemonHandoff.js +16 -3
  96. package/dist/lib/daemonIslandProfile.d.ts +19 -0
  97. package/dist/lib/daemonIslandProfile.js +41 -0
  98. package/dist/lib/drain-stdio.d.ts +22 -0
  99. package/dist/lib/drain-stdio.js +46 -0
  100. package/dist/lib/format.d.ts +32 -0
  101. package/dist/lib/format.js +105 -1
  102. package/dist/lib/initiatives-worker.d.ts +25 -0
  103. package/dist/lib/initiatives-worker.js +13 -0
  104. package/dist/lib/keychain.d.ts +22 -1
  105. package/dist/lib/keychain.js +40 -1
  106. package/dist/lib/local-daemon-readiness.js +4 -6
  107. package/dist/lib/local-skills.js +4 -1
  108. package/dist/lib/login.d.ts +7 -0
  109. package/dist/lib/login.js +5 -0
  110. package/dist/lib/machines.d.ts +68 -0
  111. package/dist/lib/machines.js +67 -0
  112. package/dist/lib/proactive-audit.d.ts +52 -0
  113. package/dist/lib/proactive-audit.js +67 -0
  114. package/dist/lib/proactiveApi.d.ts +23 -0
  115. package/dist/lib/refresh.d.ts +20 -6
  116. package/dist/lib/refresh.js +27 -9
  117. package/dist/lib/roles.d.ts +1 -1
  118. package/dist/lib/runtime-start-verification.js +3 -6
  119. package/dist/lib/schedule.d.ts +189 -9
  120. package/dist/lib/schedule.js +283 -22
  121. package/dist/lib/triggers.d.ts +134 -3
  122. package/dist/lib/triggers.js +370 -17
  123. package/dist/lib/workflow-node-control.js +8 -0
  124. package/dist/lib/workflow-run-view.js +9 -0
  125. package/dist/node_modules/@skrr-ai/auth-core/dist/cjs/configRoot.d.ts +12 -0
  126. package/dist/node_modules/@skrr-ai/auth-core/dist/cjs/configRoot.js +10 -2
  127. package/dist/node_modules/@skrr-ai/auth-core/dist/cjs/deviceIdentityBridge.d.ts +8 -0
  128. package/dist/node_modules/@skrr-ai/auth-core/dist/cjs/deviceIdentityBridge.js +22 -0
  129. package/dist/node_modules/@skrr-ai/auth-core/dist/cjs/executorStopReceiptV2.d.ts +133 -0
  130. package/dist/node_modules/@skrr-ai/auth-core/dist/cjs/executorStopReceiptV2.js +180 -0
  131. package/dist/node_modules/@skrr-ai/auth-core/dist/cjs/index.d.ts +5 -3
  132. package/dist/node_modules/@skrr-ai/auth-core/dist/cjs/index.js +50 -0
  133. package/dist/node_modules/@skrr-ai/auth-core/dist/cjs/profilePorts.d.ts +137 -0
  134. package/dist/node_modules/@skrr-ai/auth-core/dist/cjs/profilePorts.js +328 -0
  135. package/dist/node_modules/@skrr-ai/auth-core/dist/cjs/profileSelection.d.ts +63 -0
  136. package/dist/node_modules/@skrr-ai/auth-core/dist/cjs/profileSelection.js +174 -0
  137. package/dist/node_modules/@skrr-ai/auth-core/dist/cjs/refresh.d.ts +22 -0
  138. package/dist/node_modules/@skrr-ai/auth-core/dist/cjs/refresh.js +15 -4
  139. package/dist/node_modules/@skrr-ai/auth-core/dist/esm/configRoot.d.ts +12 -0
  140. package/dist/node_modules/@skrr-ai/auth-core/dist/esm/configRoot.js +14 -0
  141. package/dist/node_modules/@skrr-ai/auth-core/dist/esm/deviceIdentityBridge.d.ts +8 -0
  142. package/dist/node_modules/@skrr-ai/auth-core/dist/esm/deviceIdentityBridge.js +27 -0
  143. package/dist/node_modules/@skrr-ai/auth-core/dist/esm/executorStopReceiptV2.d.ts +133 -0
  144. package/dist/node_modules/@skrr-ai/auth-core/dist/esm/executorStopReceiptV2.js +183 -0
  145. package/dist/node_modules/@skrr-ai/auth-core/dist/esm/index.d.ts +5 -3
  146. package/dist/node_modules/@skrr-ai/auth-core/dist/esm/index.js +11 -3
  147. package/dist/node_modules/@skrr-ai/auth-core/dist/esm/profilePorts.d.ts +137 -0
  148. package/dist/node_modules/@skrr-ai/auth-core/dist/esm/profilePorts.js +333 -0
  149. package/dist/node_modules/@skrr-ai/auth-core/dist/esm/profileSelection.d.ts +63 -0
  150. package/dist/node_modules/@skrr-ai/auth-core/dist/esm/profileSelection.js +212 -0
  151. package/dist/node_modules/@skrr-ai/auth-core/dist/esm/refresh.d.ts +22 -0
  152. package/dist/node_modules/@skrr-ai/auth-core/dist/esm/refresh.js +22 -4
  153. package/dist/node_modules/@skrr-ai/auth-core/package.json +11 -1
  154. package/dist/node_modules/@skrr-ai/data-provider/index.js +7446 -7378
  155. package/oclif.manifest.json +844 -47
  156. package/package.json +1 -1
@@ -0,0 +1,333 @@
1
+ /**
2
+ * profilePorts.ts — which loopback ports a daemon profile listens on, and why.
3
+ *
4
+ * Every daemon profile on a machine runs a health server and a browser relay on
5
+ * loopback. Their default ports used to be DERIVED: `base + fnv1a32(profile) % 100`.
6
+ * A hundred slots is a birthday problem (an even chance of some collision at
7
+ * about twelve profiles), and a colliding pair of names collides every time.
8
+ * Measured on one machine: `default`, `commitment-local` and
9
+ * `df-261101-gateway-v139` all derive health 19674 and relay 18886 (OSK-22134,
10
+ * OSK-22128). The second profile could not start its relay, and its `status`
11
+ * read the first profile's health server as its own.
12
+ *
13
+ * So the port is now ASSIGNED, by one owner: the daemon that holds a profile's
14
+ * singleton lock records the profile's ports in `<root>/port-allocations.json`
15
+ * when it starts (`daemon/src/config/port-allocation.ts`), and everyone else
16
+ * READS that record through this module. Resolution, for each of the two ports:
17
+ *
18
+ * 1. an explicit port in the profile's `daemon.json` — `explicit`;
19
+ * 2. the profile's entry in the allocation record — `allocated`;
20
+ * 3. the derived port, as before — `derived` (a profile whose daemon has not
21
+ * started since allocation existed, or a reader on a machine without the
22
+ * record);
23
+ *
24
+ * and `OVERSKY_STATIC_DEFAULT_PORTS=1` still means the legacy fixed defaults
25
+ * (`static`), with no record read or written.
26
+ *
27
+ * A `daemon.json` value EQUAL TO THE DERIVED PORT is not explicit. `saveConfig`
28
+ * wrote the whole `health` and `browser` blocks on every login and `config`, so
29
+ * almost every profile carries its derived port on disk, indistinguishable from
30
+ * a choice — the same reasoning `saveConfig` already applies to shipped limits.
31
+ * Honouring those would freeze every existing collision as "explicit". A real
32
+ * choice is a value that differs from the derived one.
33
+ *
34
+ * Lives in auth-core because the daemon, its CLI commands and the desktop app
35
+ * all need the same answer, and the desktop cannot import the daemon's config
36
+ * hub. Dependency-free (node builtins only) and read-only: allocation, which
37
+ * writes, belongs to the daemon alone.
38
+ */
39
+ import fs from 'node:fs';
40
+ import path from 'node:path';
41
+ export const HEALTH_BASE_PORT = 19580;
42
+ export const BROWSER_RELAY_BASE_PORT = 18792;
43
+ /** Each kind owns `[base, base + PROFILE_PORT_RANGE)`. */
44
+ export const PROFILE_PORT_RANGE = 100;
45
+ export const PORT_ALLOCATIONS_FILENAME = 'port-allocations.json';
46
+ export const PORT_ALLOCATIONS_VERSION = 1;
47
+ /** The kill switch: legacy fixed defaults, no allocation. */
48
+ export const STATIC_DEFAULT_PORTS_ENV = 'OVERSKY_STATIC_DEFAULT_PORTS';
49
+ export const DEFAULT_PORT_PROFILE = 'default';
50
+ export const PROFILE_PORT_KINDS = ['health', 'relay'];
51
+ export function profilePortBase(kind) {
52
+ return kind === 'health' ? HEALTH_BASE_PORT : BROWSER_RELAY_BASE_PORT;
53
+ }
54
+ /** FNV-1a 32-bit over a string's UTF-16 code units. Pure. */
55
+ export function fnv1a32(str) {
56
+ let h = 0x811c9dc5;
57
+ for (let i = 0; i < str.length; i++) {
58
+ h ^= str.charCodeAt(i);
59
+ h = Math.imul(h, 0x01000193) >>> 0;
60
+ }
61
+ return h >>> 0;
62
+ }
63
+ export function staticDefaultPortsEnabled(env = process.env) {
64
+ return env[STATIC_DEFAULT_PORTS_ENV] === '1';
65
+ }
66
+ /**
67
+ * `base + fnv1a32(profile) % 100`, or `base` under the kill switch. The legacy
68
+ * default and the starting point of every allocation; never, on its own, an
69
+ * answer to "which port does this profile listen on".
70
+ */
71
+ export function profileDerivedPort(basePort, profile, env = process.env) {
72
+ if (staticDefaultPortsEnabled(env))
73
+ return basePort;
74
+ return basePort + (fnv1a32(profile) % PROFILE_PORT_RANGE);
75
+ }
76
+ export function derivedProfilePort(kind, profile, env = process.env) {
77
+ return profileDerivedPort(profilePortBase(kind), profile, env);
78
+ }
79
+ export function isInProfilePortRange(kind, port) {
80
+ const base = profilePortBase(kind);
81
+ return (typeof port === 'number' &&
82
+ Number.isInteger(port) &&
83
+ port >= base &&
84
+ port < base + PROFILE_PORT_RANGE);
85
+ }
86
+ export function portAllocationsPath(root) {
87
+ return path.join(root, PORT_ALLOCATIONS_FILENAME);
88
+ }
89
+ export function emptyPortAllocations() {
90
+ return { version: PORT_ALLOCATIONS_VERSION, profiles: {} };
91
+ }
92
+ const MOVE_REASONS = new Set([
93
+ 'default_priority',
94
+ 'held_by_profile',
95
+ 'in_use',
96
+ 'range_exhausted',
97
+ ]);
98
+ function parseMove(raw, kind) {
99
+ if (!raw || typeof raw !== 'object')
100
+ return undefined;
101
+ const m = raw;
102
+ if (!isInProfilePortRange(kind, m.from) || typeof m.reason !== 'string')
103
+ return undefined;
104
+ if (!MOVE_REASONS.has(m.reason))
105
+ return undefined;
106
+ return {
107
+ from: m.from,
108
+ reason: m.reason,
109
+ ...(typeof m.profile === 'string' ? { profile: m.profile } : {}),
110
+ ...(typeof m.at === 'string' ? { at: m.at } : {}),
111
+ };
112
+ }
113
+ /**
114
+ * Tolerant parse: an entry that is not a port in its kind's range is dropped,
115
+ * so a hand-edited or truncated record degrades to "derived" for that profile
116
+ * rather than handing a reader a port the allocator would never have chosen.
117
+ */
118
+ export function parsePortAllocations(raw) {
119
+ const out = emptyPortAllocations();
120
+ if (!raw || typeof raw !== 'object')
121
+ return out;
122
+ const profiles = raw.profiles;
123
+ if (!profiles || typeof profiles !== 'object' || Array.isArray(profiles))
124
+ return out;
125
+ for (const [name, value] of Object.entries(profiles)) {
126
+ if (!value || typeof value !== 'object')
127
+ continue;
128
+ const v = value;
129
+ const entry = {};
130
+ for (const kind of PROFILE_PORT_KINDS) {
131
+ if (isInProfilePortRange(kind, v[kind]))
132
+ entry[kind] = v[kind];
133
+ const move = parseMove(v.moves?.[kind], kind);
134
+ if (move && entry[kind] !== undefined)
135
+ entry.moves = { ...entry.moves, [kind]: move };
136
+ }
137
+ if (typeof v.updatedAt === 'string')
138
+ entry.updatedAt = v.updatedAt;
139
+ if (entry.health !== undefined || entry.relay !== undefined)
140
+ out.profiles[name] = entry;
141
+ }
142
+ return out;
143
+ }
144
+ /** The record under `root`, or an empty one when it is absent or unreadable. */
145
+ export function readPortAllocations(root) {
146
+ try {
147
+ return parsePortAllocations(JSON.parse(fs.readFileSync(portAllocationsPath(root), 'utf8')));
148
+ }
149
+ catch {
150
+ return emptyPortAllocations();
151
+ }
152
+ }
153
+ /** Parse a configured port the way `loadConfig` coerces numbers. */
154
+ function configuredPortNumber(value) {
155
+ let n = null;
156
+ if (typeof value === 'number')
157
+ n = value;
158
+ else if (typeof value === 'string' && value.trim() !== '')
159
+ n = Number(value);
160
+ if (n === null || !Number.isInteger(n) || n < 0 || n > 65535)
161
+ return null;
162
+ return n;
163
+ }
164
+ /**
165
+ * A `daemon.json` port that is a real choice, or null. Absent, unparsable and
166
+ * equal-to-derived all read as "no choice" (see the header for why the last).
167
+ * `0` is a choice (an ephemeral bind) and is returned as 0.
168
+ */
169
+ export function explicitProfilePort(kind, configured, profile, env = process.env) {
170
+ const n = configuredPortNumber(configured);
171
+ if (n === null)
172
+ return null;
173
+ return n === derivedProfilePort(kind, profile, env) ? null : n;
174
+ }
175
+ export function profileDaemonJsonPath(root, profile) {
176
+ return path.join(root, 'profiles', profile, 'daemon.json');
177
+ }
178
+ /** The raw port values in a profile's `daemon.json`; both undefined when unreadable. */
179
+ export function readDaemonJsonPortValues(root, profile) {
180
+ try {
181
+ const parsed = JSON.parse(fs.readFileSync(profileDaemonJsonPath(root, profile), 'utf8'));
182
+ return { health: parsed?.health?.port, relay: parsed?.browser?.relayPort };
183
+ }
184
+ catch {
185
+ return { health: undefined, relay: undefined };
186
+ }
187
+ }
188
+ /** One port, from inputs the caller already holds. */
189
+ export function resolveProfilePort(input) {
190
+ const env = input.env ?? process.env;
191
+ const derived = derivedProfilePort(input.kind, input.profile, env);
192
+ const explicit = explicitProfilePort(input.kind, input.configured, input.profile, env);
193
+ if (explicit !== null)
194
+ return { kind: input.kind, port: explicit, source: 'explicit', derived };
195
+ if (staticDefaultPortsEnabled(env)) {
196
+ return { kind: input.kind, port: derived, source: 'static', derived };
197
+ }
198
+ const entry = input.allocations.profiles[input.profile];
199
+ const allocated = entry?.[input.kind];
200
+ if (isInProfilePortRange(input.kind, allocated)) {
201
+ const move = entry?.moves?.[input.kind];
202
+ return {
203
+ kind: input.kind,
204
+ port: allocated,
205
+ source: 'allocated',
206
+ derived,
207
+ ...(move && allocated !== derived ? { move } : {}),
208
+ };
209
+ }
210
+ return { kind: input.kind, port: derived, source: 'derived', derived };
211
+ }
212
+ /**
213
+ * Both ports of `profile` under `root`. Pass `configured` when the caller has
214
+ * already parsed the profile's `daemon.json` (the daemon's `loadConfig` does),
215
+ * so the file is not read twice and the two cannot disagree.
216
+ */
217
+ export function resolveProfilePorts(root, profile, options = {}) {
218
+ const env = options.env ?? process.env;
219
+ const configured = options.configured ?? readDaemonJsonPortValues(root, profile);
220
+ const allocations = options.allocations ??
221
+ (staticDefaultPortsEnabled(env) ? emptyPortAllocations() : readPortAllocations(root));
222
+ return {
223
+ profile,
224
+ health: resolveProfilePort({
225
+ kind: 'health',
226
+ profile,
227
+ configured: configured.health,
228
+ allocations,
229
+ env,
230
+ }),
231
+ relay: resolveProfilePort({
232
+ kind: 'relay',
233
+ profile,
234
+ configured: configured.relay,
235
+ allocations,
236
+ env,
237
+ }),
238
+ };
239
+ }
240
+ /** The profile directories under `root/profiles`. */
241
+ export function listProfileNames(root) {
242
+ try {
243
+ return fs
244
+ .readdirSync(path.join(root, 'profiles'), { withFileTypes: true })
245
+ .filter((d) => d.isDirectory() && !d.name.startsWith('.'))
246
+ .map((d) => d.name)
247
+ .sort();
248
+ }
249
+ catch {
250
+ return [];
251
+ }
252
+ }
253
+ /**
254
+ * Every OTHER profile's claim on each port of `kind`: its explicit port, else
255
+ * its recorded allocation, plus the `default` profile's derived port, which is
256
+ * reserved for it even before it has a record. This is the set an allocation
257
+ * must avoid, and what a reader shows when a derived port is shared.
258
+ */
259
+ export function otherProfilePortClaims(root, kind, profile, options = {}) {
260
+ const env = options.env ?? process.env;
261
+ const allocations = options.allocations ?? readPortAllocations(root);
262
+ const claims = new Map();
263
+ const names = new Set([...listProfileNames(root), ...Object.keys(allocations.profiles)]);
264
+ names.delete(profile);
265
+ for (const other of [...names].sort()) {
266
+ const explicit = explicitProfilePort(kind, readDaemonJsonPortValues(root, other)[kind], other, env);
267
+ if (explicit !== null) {
268
+ // 0 is an ephemeral bind, not a claim on any port.
269
+ if (explicit > 0 && !claims.has(explicit))
270
+ claims.set(explicit, { profile: other, how: 'explicit' });
271
+ continue;
272
+ }
273
+ const recorded = allocations.profiles[other]?.[kind];
274
+ if (isInProfilePortRange(kind, recorded) && !claims.has(recorded)) {
275
+ claims.set(recorded, { profile: other, how: 'allocated' });
276
+ }
277
+ }
278
+ if (profile !== DEFAULT_PORT_PROFILE) {
279
+ const reserved = derivedProfilePort(kind, DEFAULT_PORT_PROFILE, env);
280
+ if (!claims.has(reserved)) {
281
+ claims.set(reserved, { profile: DEFAULT_PORT_PROFILE, how: 'default_priority' });
282
+ }
283
+ }
284
+ return claims;
285
+ }
286
+ const KIND_LABEL = { health: 'health', relay: 'browser relay' };
287
+ const CLAIM_PHRASES = {
288
+ explicit: 'sets it explicitly',
289
+ allocated: 'is allocated it',
290
+ default_priority: 'has priority on it',
291
+ };
292
+ /**
293
+ * One sentence: which port, from where, and — when it is not the derived one or
294
+ * might be shared — why. `sharedWith` is a claim another profile holds on this
295
+ * port (from `otherProfilePortClaims`); pass it for a `derived` port, which is
296
+ * the one case where a reader can see a collision the daemon has not resolved.
297
+ */
298
+ export function describeProfilePort(resolved, sharedWith) {
299
+ const label = `${KIND_LABEL[resolved.kind]} port ${resolved.port}`;
300
+ switch (resolved.source) {
301
+ case 'explicit':
302
+ return `${label} (explicit: set in this profile's daemon.json)`;
303
+ case 'static':
304
+ return `${label} (fixed default: ${STATIC_DEFAULT_PORTS_ENV}=1)`;
305
+ case 'allocated': {
306
+ if (resolved.port === resolved.derived) {
307
+ return `${label} (allocated: this profile's derived port)`;
308
+ }
309
+ const move = resolved.move;
310
+ const from = `its derived port ${resolved.derived}`;
311
+ if (!move)
312
+ return `${label} (allocated: moved off ${from})`;
313
+ switch (move.reason) {
314
+ case 'default_priority':
315
+ return `${label} (allocated: ${from} is reserved for the default profile)`;
316
+ case 'held_by_profile':
317
+ return `${label} (allocated: ${from} is held by profile '${move.profile ?? 'unknown'}')`;
318
+ case 'in_use':
319
+ return `${label} (allocated: ${from} was in use by another process)`;
320
+ case 'range_exhausted':
321
+ return `${label} (allocated: no free port in range; kept ${from})`;
322
+ }
323
+ return `${label} (allocated)`;
324
+ }
325
+ case 'derived':
326
+ if (sharedWith) {
327
+ return (`${label} (derived from the profile name, not yet allocated, and SHARED: ` +
328
+ `profile '${sharedWith.profile}' ${CLAIM_PHRASES[sharedWith.how]}; ` +
329
+ `restart this profile's daemon to be allocated its own)`);
330
+ }
331
+ return `${label} (derived from the profile name; allocated when this profile's daemon next starts)`;
332
+ }
333
+ }
@@ -0,0 +1,63 @@
1
+ /** Canonical default profile name. Used when no flag / env / lock is set. */
2
+ export declare const DEFAULT_PROFILE = "default";
3
+ /** Basename of the sticky selector at the skrr root (`skrrd profile use`). */
4
+ export declare const PROFILE_LOCK_FILENAME = "profile.lock";
5
+ /** Environment variable that selects a profile for one process tree. */
6
+ export declare const PROFILE_ENV_VAR = "OVERSKY_PROFILE";
7
+ export type ProfileSelectionSource = 'flag' | 'env' | 'lock' | 'default';
8
+ export interface ProfileSelection {
9
+ profile: string;
10
+ source: ProfileSelectionSource;
11
+ }
12
+ /**
13
+ * Validate a profile name. Throws `Error` with a human-readable message on
14
+ * invalid input. Never writes anywhere — pure predicate.
15
+ */
16
+ export declare function assertValidProfileName(name: string): void;
17
+ /** Non-throwing variant of `assertValidProfileName`. */
18
+ export declare function isValidProfileName(name: unknown): name is string;
19
+ /** Where the sticky selector lives for this environment's skrr root. */
20
+ export declare function profileLockPath(env?: NodeJS.ProcessEnv): string;
21
+ /**
22
+ * Read the sticky selector. Returns `null` when the file is absent, empty,
23
+ * unreadable, or names an invalid profile — a corrupted lock must never pin a
24
+ * command to a profile that cannot exist.
25
+ */
26
+ export declare function readProfileLock(env?: NodeJS.ProcessEnv): string | null;
27
+ export interface ResolveProfileSelectionInput {
28
+ /** The `--profile` value, or null/undefined/'' when the flag was not given. */
29
+ flag?: string | null;
30
+ /** Environment to read `OVERSKY_PROFILE` and the root from. Default: `process.env`. */
31
+ env?: NodeJS.ProcessEnv;
32
+ /**
33
+ * Whether to consult `OVERSKY_PROFILE` and the lock at all. Tests pass
34
+ * `false` to pin the output to `flag ?? DEFAULT_PROFILE`.
35
+ */
36
+ readEnv?: boolean;
37
+ }
38
+ /**
39
+ * Resolve the profile for one command invocation:
40
+ * `--profile` > `OVERSKY_PROFILE` > `<root>/profile.lock` > `default`.
41
+ *
42
+ * An invalid flag or environment value THROWS (with the grammar's message): a
43
+ * name the person typed is a request, and silently replacing it with another
44
+ * profile would act on the wrong credentials. An invalid lock is ignored, as a
45
+ * corrupt file should be.
46
+ *
47
+ * Pure apart from reading the lock; mutates no global state.
48
+ */
49
+ export declare function resolveProfileSelection(input?: ResolveProfileSelectionInput): ProfileSelection;
50
+ /**
51
+ * The argv a process passes to the OTHER binary so the child acts on exactly
52
+ * `profile`. Always explicit, `default` included — see rule 2 above.
53
+ */
54
+ export declare function explicitProfileArgs(profile: string): string[];
55
+ /**
56
+ * Does a command typed WITHOUT `--profile` in this environment act on
57
+ * `profile`? A person-facing hint can then omit the flag when it would be
58
+ * noise, and must include it when the environment or the lock would send the
59
+ * typed command somewhere else.
60
+ */
61
+ export declare function profileIsImplicit(profile: string, env?: NodeJS.ProcessEnv): boolean;
62
+ /** One sentence naming the profile and why it was chosen, for diagnostics. */
63
+ export declare function describeProfileSelection(selection: ProfileSelection, env?: NodeJS.ProcessEnv): string;
@@ -0,0 +1,212 @@
1
+ /**
2
+ * profileSelection.ts — the ONE rule for which profile a `skrr` or `skrrd`
3
+ * command acts on.
4
+ *
5
+ * A profile is the unit of credential and state isolation on a machine
6
+ * (`<root>/profiles/<name>/`). Both binaries choose one before they touch a
7
+ * credential, and they used to choose by different rules:
8
+ *
9
+ * - `skrrd`: `--profile` > `OVERSKY_PROFILE` > `<root>/profile.lock` > `default`
10
+ * - `skrr`: `--profile` > `OVERSKY_PROFILE` > `default` (no lock)
11
+ *
12
+ * So after `skrrd profile use work`, `skrr login` signed the CLI into `default`
13
+ * and handed the daemon credential to whatever `skrrd accept-handoff` resolved
14
+ * on its own — `work`, through the lock (OSK-22298, OSK-22299). Each program was
15
+ * right by its own rule; the lock had two readers that disagreed about what it
16
+ * meant. The same shape as `configRoot.ts` one level down, and the same fix:
17
+ * the answer is READ from one function, never re-derived.
18
+ *
19
+ * Two rules keep the binaries from drifting again:
20
+ *
21
+ * 1. Both resolve through `resolveProfileSelection`, with the same precedence
22
+ * and the same name grammar.
23
+ * 2. A process that spawns the other binary passes the profile it resolved
24
+ * EXPLICITLY (`--profile <name>`, `default` included). The child's own
25
+ * resolution would agree today, but only while both see the same
26
+ * environment and the same lock; an explicit flag makes the hand-off
27
+ * independent of either.
28
+ *
29
+ * Takes `env` rather than reading the global so a caller can resolve for a
30
+ * child it is about to spawn, and so tests need no process-wide mutation.
31
+ */
32
+ import fs from 'node:fs';
33
+ import path from 'node:path';
34
+ import { resolveConfigRoot } from './configRoot.js';
35
+ /** Canonical default profile name. Used when no flag / env / lock is set. */
36
+ export const DEFAULT_PROFILE = 'default';
37
+ /** Basename of the sticky selector at the skrr root (`skrrd profile use`). */
38
+ export const PROFILE_LOCK_FILENAME = 'profile.lock';
39
+ /** Environment variable that selects a profile for one process tree. */
40
+ export const PROFILE_ENV_VAR = 'OVERSKY_PROFILE';
41
+ /**
42
+ * Profile name grammar. Intentionally strict:
43
+ * - letters, digits, dot, dash, underscore
44
+ * - must start with [A-Za-z0-9]
45
+ * - 1–64 chars
46
+ *
47
+ * Rejects path traversal (`..`, `/`, `\`), shell metacharacters, and
48
+ * leading-dot hidden names. A profile name becomes a directory name, a Keychain
49
+ * service suffix and an OS service label, so a name that is not valid here must
50
+ * never reach any of them.
51
+ */
52
+ const VALID_PROFILE_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
53
+ /**
54
+ * Names that collide with files at the root of the skrr directory or with
55
+ * migration bookkeeping. The `.migrated*` entries are already rejected by the
56
+ * grammar (leading dot) and are kept so a future relaxation cannot admit them.
57
+ */
58
+ const RESERVED_PROFILE_NAMES = new Set([
59
+ 'profiles',
60
+ 'profile',
61
+ '.migrated',
62
+ '.migrated-2026-Q3-phase-k',
63
+ ]);
64
+ /**
65
+ * Windows reserved device names. NTFS refuses them as a basename (with or
66
+ * without an extension, case-insensitively), and the failure surfaces deep in
67
+ * `CreateDirectory` with a cryptic message. Rejected up front, on every
68
+ * platform, so a profile created on one OS is usable on another.
69
+ */
70
+ const WINDOWS_RESERVED_NAMES = new Set([
71
+ 'con',
72
+ 'prn',
73
+ 'aux',
74
+ 'nul',
75
+ 'com1',
76
+ 'com2',
77
+ 'com3',
78
+ 'com4',
79
+ 'com5',
80
+ 'com6',
81
+ 'com7',
82
+ 'com8',
83
+ 'com9',
84
+ 'lpt1',
85
+ 'lpt2',
86
+ 'lpt3',
87
+ 'lpt4',
88
+ 'lpt5',
89
+ 'lpt6',
90
+ 'lpt7',
91
+ 'lpt8',
92
+ 'lpt9',
93
+ ]);
94
+ /**
95
+ * Validate a profile name. Throws `Error` with a human-readable message on
96
+ * invalid input. Never writes anywhere — pure predicate.
97
+ */
98
+ export function assertValidProfileName(name) {
99
+ if (typeof name !== 'string' || name.length === 0) {
100
+ throw new Error('Profile name must be a non-empty string.');
101
+ }
102
+ if (!VALID_PROFILE_RE.test(name)) {
103
+ throw new Error(`Invalid profile name "${name}". Profile names must be 1–64 ` +
104
+ `characters and contain only letters, digits, dot, dash, or ` +
105
+ `underscore. The first character must be a letter or digit.`);
106
+ }
107
+ if (RESERVED_PROFILE_NAMES.has(name)) {
108
+ throw new Error(`Profile name "${name}" is reserved. Pick a different name.`);
109
+ }
110
+ if (WINDOWS_RESERVED_NAMES.has(name.toLowerCase())) {
111
+ throw new Error(`Profile name "${name}" is a Windows reserved device name and ` +
112
+ `cannot be used as a directory name on Windows filesystems. ` +
113
+ `Pick a different name (e.g., "${name}-ws").`);
114
+ }
115
+ }
116
+ /** Non-throwing variant of `assertValidProfileName`. */
117
+ export function isValidProfileName(name) {
118
+ if (typeof name !== 'string')
119
+ return false;
120
+ if (!VALID_PROFILE_RE.test(name))
121
+ return false;
122
+ if (RESERVED_PROFILE_NAMES.has(name))
123
+ return false;
124
+ if (WINDOWS_RESERVED_NAMES.has(name.toLowerCase()))
125
+ return false;
126
+ return true;
127
+ }
128
+ /** Where the sticky selector lives for this environment's skrr root. */
129
+ export function profileLockPath(env = process.env) {
130
+ return path.join(resolveConfigRoot(env), PROFILE_LOCK_FILENAME);
131
+ }
132
+ /**
133
+ * Read the sticky selector. Returns `null` when the file is absent, empty,
134
+ * unreadable, or names an invalid profile — a corrupted lock must never pin a
135
+ * command to a profile that cannot exist.
136
+ */
137
+ export function readProfileLock(env = process.env) {
138
+ try {
139
+ const raw = fs.readFileSync(profileLockPath(env), 'utf-8').trim();
140
+ if (!raw)
141
+ return null;
142
+ return isValidProfileName(raw) ? raw : null;
143
+ }
144
+ catch {
145
+ return null;
146
+ }
147
+ }
148
+ /**
149
+ * Resolve the profile for one command invocation:
150
+ * `--profile` > `OVERSKY_PROFILE` > `<root>/profile.lock` > `default`.
151
+ *
152
+ * An invalid flag or environment value THROWS (with the grammar's message): a
153
+ * name the person typed is a request, and silently replacing it with another
154
+ * profile would act on the wrong credentials. An invalid lock is ignored, as a
155
+ * corrupt file should be.
156
+ *
157
+ * Pure apart from reading the lock; mutates no global state.
158
+ */
159
+ export function resolveProfileSelection(input = {}) {
160
+ const flag = typeof input.flag === 'string' ? input.flag.trim() : '';
161
+ if (flag) {
162
+ assertValidProfileName(flag);
163
+ return { profile: flag, source: 'flag' };
164
+ }
165
+ if (input.readEnv === false)
166
+ return { profile: DEFAULT_PROFILE, source: 'default' };
167
+ const env = input.env ?? process.env;
168
+ const fromEnv = (env[PROFILE_ENV_VAR] ?? '').trim();
169
+ if (fromEnv) {
170
+ assertValidProfileName(fromEnv);
171
+ return { profile: fromEnv, source: 'env' };
172
+ }
173
+ const pinned = readProfileLock(env);
174
+ if (pinned)
175
+ return { profile: pinned, source: 'lock' };
176
+ return { profile: DEFAULT_PROFILE, source: 'default' };
177
+ }
178
+ /**
179
+ * The argv a process passes to the OTHER binary so the child acts on exactly
180
+ * `profile`. Always explicit, `default` included — see rule 2 above.
181
+ */
182
+ export function explicitProfileArgs(profile) {
183
+ assertValidProfileName(profile);
184
+ return ['--profile', profile];
185
+ }
186
+ /**
187
+ * Does a command typed WITHOUT `--profile` in this environment act on
188
+ * `profile`? A person-facing hint can then omit the flag when it would be
189
+ * noise, and must include it when the environment or the lock would send the
190
+ * typed command somewhere else.
191
+ */
192
+ export function profileIsImplicit(profile, env = process.env) {
193
+ try {
194
+ return resolveProfileSelection({ env }).profile === profile;
195
+ }
196
+ catch {
197
+ return false;
198
+ }
199
+ }
200
+ /** One sentence naming the profile and why it was chosen, for diagnostics. */
201
+ export function describeProfileSelection(selection, env = process.env) {
202
+ switch (selection.source) {
203
+ case 'flag':
204
+ return `profile '${selection.profile}' (from --profile)`;
205
+ case 'env':
206
+ return `profile '${selection.profile}' (from ${PROFILE_ENV_VAR})`;
207
+ case 'lock':
208
+ return `profile '${selection.profile}' (pinned by ${profileLockPath(env)})`;
209
+ default:
210
+ return `profile '${selection.profile}'`;
211
+ }
212
+ }
@@ -270,6 +270,28 @@ export declare function refreshDaemonToken(serverUrl: string, currentRefreshToke
270
270
  * replay attempt while keeping back-compat with un-upgraded servers.
271
271
  */
272
272
  export declare function revokeDaemonRefreshSession(serverUrl: string, refreshToken: string): Promise<void>;
273
+ /**
274
+ * What became of a revoke request. The server never says whether the presented
275
+ * token existed, so `accepted` is the strongest claim available: the server
276
+ * took the request, and a live session behind that token is now revoked.
277
+ * `refused` and `unreachable` mean the session, if there is one, is still live.
278
+ */
279
+ export type RefreshRevokeResult = {
280
+ outcome: 'accepted';
281
+ } | {
282
+ outcome: 'refused';
283
+ status: number;
284
+ } | {
285
+ outcome: 'unreachable';
286
+ detail: string;
287
+ };
288
+ /**
289
+ * `revokeDaemonRefreshSession` with its outcome reported instead of swallowed,
290
+ * for a caller that must not tell a person "signed out" when the server never
291
+ * heard (OSK-22307: `skrr logout` did exactly that). Same request, same body,
292
+ * same 5-second bound; it never throws.
293
+ */
294
+ export declare function revokeDaemonRefreshSessionReported(serverUrl: string, refreshToken: string): Promise<RefreshRevokeResult>;
273
295
  export declare function persistReauthState(state: ReauthState): void;
274
296
  export declare function needsReauthState(): {
275
297
  needed: boolean;
@@ -545,7 +545,24 @@ export async function refreshDaemonToken(serverUrl, currentRefreshToken, daemonI
545
545
  export async function revokeDaemonRefreshSession(serverUrl, refreshToken) {
546
546
  if (!refreshToken)
547
547
  return;
548
+ const result = await revokeDaemonRefreshSessionReported(serverUrl, refreshToken);
548
549
  const log = getAuthLogger();
550
+ if (result.outcome === 'refused') {
551
+ log.debug(`[auth/refresh] revoke returned ${result.status}`);
552
+ }
553
+ else if (result.outcome === 'unreachable') {
554
+ log.debug(`[auth/refresh] revoke network error: ${result.detail}`);
555
+ }
556
+ }
557
+ /**
558
+ * `revokeDaemonRefreshSession` with its outcome reported instead of swallowed,
559
+ * for a caller that must not tell a person "signed out" when the server never
560
+ * heard (OSK-22307: `skrr logout` did exactly that). Same request, same body,
561
+ * same 5-second bound; it never throws.
562
+ */
563
+ export async function revokeDaemonRefreshSessionReported(serverUrl, refreshToken) {
564
+ if (!refreshToken)
565
+ return { outcome: 'unreachable', detail: 'no refresh token to present' };
549
566
  const url = `${serverUrl.replace(/\/+$/, '')}/api/daemons/token/revoke`;
550
567
  const controller = new AbortController();
551
568
  const timer = setTimeout(() => controller.abort(), 5_000);
@@ -562,12 +579,13 @@ export async function revokeDaemonRefreshSession(serverUrl, refreshToken) {
562
579
  signal: controller.signal,
563
580
  });
564
581
  notifyResponseObserver(res);
565
- if (!res.ok) {
566
- log.debug(`[auth/refresh] revoke returned ${res.status}`);
567
- }
582
+ return res.ok ? { outcome: 'accepted' } : { outcome: 'refused', status: res.status };
568
583
  }
569
584
  catch (err) {
570
- log.debug(`[auth/refresh] revoke network error: ${err?.message}`);
585
+ const detail = controller.signal.aborted
586
+ ? 'no answer within 5 seconds'
587
+ : err?.message || String(err);
588
+ return { outcome: 'unreachable', detail };
571
589
  }
572
590
  finally {
573
591
  clearTimeout(timer);