@amerged/ohmyhost-cli 0.1.74 → 0.1.76
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/README.md +1 -1
- package/dist/bin.js +1 -1
- package/dist/{chunk-PTRLVTTT.js → chunk-N6LDQC3B.js} +1188 -496
- package/dist/index.js +26 -140
- package/package.json +1 -1
- package/src/apps/product-cli/package.json +1 -1
- package/src/apps/product-cli/src/cli.ts +180 -60
- package/src/apps/product-cli/src/composition.ts +132 -48
- package/src/apps/product-cli/src/credential-refresh.ts +65 -0
- package/src/apps/product-cli/src/file-credential-store.ts +131 -57
- package/src/apps/product-cli/src/index.ts +2 -0
- package/src/apps/product-cli/src/login-ownership.ts +291 -0
- package/src/apps/product-cli/src/profile-store.ts +303 -39
- package/src/apps/product-cli/src/runtime-contract.ts +12 -1
- package/src/apps/product-cli/src/workspace.ts +41 -27
- package/src/packages/contracts/package.json +5 -0
- package/src/packages/contracts/src/chat-guidance.ts +102 -0
- package/src/packages/contracts/src/preview-view.ts +7 -3
- package/src/packages/contracts/src/problem-policy.ts +6 -6
- package/src/packages/sdk-ts/package.json +1 -1
- package/src/packages/sdk-ts/src/generated/index.ts +1 -0
- package/src/packages/sdk-ts/src/generated/mcp-remote.gen.ts +138 -14
- package/src/packages/sdk-ts/src/generated/types.gen.ts +17 -4
|
@@ -1,7 +1,8 @@
|
|
|
1
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
1
2
|
import { randomUUID } from "node:crypto";
|
|
2
|
-
import { link, mkdir, open, readFile, readdir, unlink } from "node:fs/promises";
|
|
3
|
+
import { link, mkdir, open, readFile, readdir, rmdir, unlink } from "node:fs/promises";
|
|
3
4
|
import { homedir } from "node:os";
|
|
4
|
-
import { join } from "node:path";
|
|
5
|
+
import { join, relative, sep } from "node:path";
|
|
5
6
|
|
|
6
7
|
import {
|
|
7
8
|
CredentialStoreIntegrityError,
|
|
@@ -13,6 +14,15 @@ import {
|
|
|
13
14
|
type CurrentCredential,
|
|
14
15
|
type KeyringEntryFactory,
|
|
15
16
|
} from "./credential-store.js";
|
|
17
|
+
import { OwnerOnlyFileCredentialStore } from "./file-credential-store.js";
|
|
18
|
+
import {
|
|
19
|
+
LoginOwnership,
|
|
20
|
+
LoginOwnershipTimeoutError,
|
|
21
|
+
linuxProcessProbe,
|
|
22
|
+
quietly,
|
|
23
|
+
type LoginOwnershipHold,
|
|
24
|
+
type ProcessProbe,
|
|
25
|
+
} from "./login-ownership.js";
|
|
16
26
|
|
|
17
27
|
/**
|
|
18
28
|
* One saved interactive login: a verified user signed in to at most one organization. The name is
|
|
@@ -25,8 +35,13 @@ export interface LocalProfile {
|
|
|
25
35
|
readonly organizationName: string | null;
|
|
26
36
|
}
|
|
27
37
|
|
|
38
|
+
/** A login that can be owned: a saved one, or the single entry of clients before named profiles. */
|
|
39
|
+
export type LoginRef = LocalProfile | "legacy";
|
|
40
|
+
|
|
28
41
|
/** Saved logins of one platform environment: a non-secret index and one secret entry each. */
|
|
29
42
|
export interface ProfileRegistry {
|
|
43
|
+
/** Where the logins are kept: owner-only files, or the operating system's credential store. */
|
|
44
|
+
readonly kind: "file" | "native";
|
|
30
45
|
list(): Promise<readonly LocalProfile[]>;
|
|
31
46
|
credential(profile: LocalProfile): CredentialStore;
|
|
32
47
|
/**
|
|
@@ -41,6 +56,22 @@ export interface ProfileRegistry {
|
|
|
41
56
|
remove(profile: LocalProfile): Promise<void>;
|
|
42
57
|
/** The single entry of clients before named profiles, read only to migrate it. */
|
|
43
58
|
legacy(): CredentialStore;
|
|
59
|
+
/**
|
|
60
|
+
* Proves that this store can save and remove a login and write the index, and leaves nothing
|
|
61
|
+
* behind. It uses a random private name that no login can have, so no saved login is touched.
|
|
62
|
+
*/
|
|
63
|
+
prove(): Promise<void>;
|
|
64
|
+
/**
|
|
65
|
+
* Runs `operation` while this process alone may change these logins. Every operation that spends a
|
|
66
|
+
* refresh token, or writes or removes a credential or its index entry, runs inside it. A nested
|
|
67
|
+
* call inside the same operation owns nothing new. Where the store cannot be shared between
|
|
68
|
+
* processes this is a direct call.
|
|
69
|
+
*/
|
|
70
|
+
owning<Result>(
|
|
71
|
+
logins: readonly LoginRef[],
|
|
72
|
+
operation: () => Promise<Result>,
|
|
73
|
+
signal?: AbortSignal,
|
|
74
|
+
): Promise<Result>;
|
|
44
75
|
}
|
|
45
76
|
|
|
46
77
|
/** The requested name already belongs to a login of another user or organization. */
|
|
@@ -59,6 +90,13 @@ export class ProfileLimitError extends Error {
|
|
|
59
90
|
}
|
|
60
91
|
}
|
|
61
92
|
|
|
93
|
+
/** A credential that proves a store works; it is removed at once and is no login. */
|
|
94
|
+
const PROBE_CREDENTIAL = (): CurrentCredential => ({
|
|
95
|
+
accessToken: "probe",
|
|
96
|
+
refreshToken: "probe",
|
|
97
|
+
expiresAt: new Date().toISOString(),
|
|
98
|
+
});
|
|
99
|
+
|
|
62
100
|
const MAX_PROFILES = 64;
|
|
63
101
|
/** Each lost race means another writer finished a change, so this bounds concurrent writers. */
|
|
64
102
|
const MAX_INDEX_ATTEMPTS = 64;
|
|
@@ -103,26 +141,95 @@ const admitProfile = (next: readonly LocalProfile[], profile: LocalProfile): voi
|
|
|
103
141
|
};
|
|
104
142
|
|
|
105
143
|
/**
|
|
106
|
-
*
|
|
107
|
-
* is
|
|
144
|
+
* The saved logins of one environment: a non-secret file index and one secret entry each. The list
|
|
145
|
+
* of logins is separate from the secrets, so saving or removing one login never rewrites a shared
|
|
108
146
|
* credential entry that another process may be changing at the same moment.
|
|
109
147
|
*/
|
|
110
|
-
|
|
111
|
-
readonly #createEntry: KeyringEntryFactory;
|
|
148
|
+
abstract class IndexedProfileRegistry implements ProfileRegistry {
|
|
112
149
|
readonly #index: ProfileIndexFiles;
|
|
113
150
|
|
|
151
|
+
protected constructor(indexDirectory: string) {
|
|
152
|
+
this.#index = new ProfileIndexFiles(indexDirectory);
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
public abstract readonly kind: "file" | "native";
|
|
156
|
+
|
|
157
|
+
public abstract credential(profile: LocalProfile): CredentialStore;
|
|
158
|
+
|
|
159
|
+
public abstract legacy(): CredentialStore;
|
|
160
|
+
|
|
161
|
+
public abstract owning<Result>(
|
|
162
|
+
logins: readonly LoginRef[],
|
|
163
|
+
operation: () => Promise<Result>,
|
|
164
|
+
signal?: AbortSignal,
|
|
165
|
+
): Promise<Result>;
|
|
166
|
+
|
|
167
|
+
/** Saves and removes one probe login with a name that is not a login name. */
|
|
168
|
+
protected abstract proveCredential(): Promise<void>;
|
|
169
|
+
|
|
170
|
+
public async prove(): Promise<void> {
|
|
171
|
+
await this.#index.probe();
|
|
172
|
+
await this.proveCredential();
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
public async list(): Promise<readonly LocalProfile[]> {
|
|
176
|
+
return (await this.#index.read()).profiles;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
public async save(
|
|
180
|
+
profile: LocalProfile,
|
|
181
|
+
credential: CurrentCredential,
|
|
182
|
+
replaces?: LocalProfile,
|
|
183
|
+
): Promise<void> {
|
|
184
|
+
assertProfile(profile);
|
|
185
|
+
await this.owning(replaces === undefined ? [profile] : [profile, replaces], async () => {
|
|
186
|
+
// Refused before anything is written, so a conflicting or surplus login changes nothing.
|
|
187
|
+
const before = await this.list();
|
|
188
|
+
admitProfile(nextProfileIndex(before, profile, replaces), profile);
|
|
189
|
+
await this.credential(profile).replace(credential);
|
|
190
|
+
try {
|
|
191
|
+
await this.#index.update((current) => {
|
|
192
|
+
const next = nextProfileIndex(current, profile, replaces);
|
|
193
|
+
admitProfile(next, profile);
|
|
194
|
+
return next;
|
|
195
|
+
});
|
|
196
|
+
} catch (error) {
|
|
197
|
+
// Another process changed the index meanwhile, or it could not be written: a login new to
|
|
198
|
+
// this computer leaves no token behind that no index entry names.
|
|
199
|
+
if (!before.some((saved) => sameLogin(saved, profile)))
|
|
200
|
+
await this.credential(profile).clear();
|
|
201
|
+
throw error;
|
|
202
|
+
}
|
|
203
|
+
if (replaces !== undefined && !sameLogin(replaces, profile))
|
|
204
|
+
await this.credential(replaces).clear();
|
|
205
|
+
});
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
public async remove(profile: LocalProfile): Promise<void> {
|
|
209
|
+
await this.owning([profile], async () => {
|
|
210
|
+
await this.credential(profile).clear();
|
|
211
|
+
await this.#index.update((current) =>
|
|
212
|
+
current.some((saved) => sameLogin(saved, profile))
|
|
213
|
+
? current.filter((saved) => !sameLogin(saved, profile))
|
|
214
|
+
: undefined,
|
|
215
|
+
);
|
|
216
|
+
});
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/** Tokens stay in the operating system's credential store, one entry per login. */
|
|
221
|
+
export class NativeKeyringProfileRegistry extends IndexedProfileRegistry {
|
|
222
|
+
public readonly kind = "native";
|
|
223
|
+
readonly #createEntry: KeyringEntryFactory;
|
|
224
|
+
|
|
114
225
|
public constructor(
|
|
115
226
|
createEntry: KeyringEntryFactory | undefined = undefined,
|
|
116
227
|
private readonly serviceName = "ohmyhost",
|
|
117
228
|
indexDirectory?: string,
|
|
118
229
|
) {
|
|
119
230
|
if (!SERVICE_NAME.test(serviceName)) throw new CredentialStoreUnavailableError();
|
|
231
|
+
super(indexDirectory ?? profileIndexDirectory(serviceName));
|
|
120
232
|
this.#createEntry = createEntry ?? createNativeEntryFactory(serviceName);
|
|
121
|
-
this.#index = new ProfileIndexFiles(indexDirectory ?? profileIndexDirectory(serviceName));
|
|
122
|
-
}
|
|
123
|
-
|
|
124
|
-
public async list(): Promise<readonly LocalProfile[]> {
|
|
125
|
-
return (await this.#index.read()).profiles;
|
|
126
233
|
}
|
|
127
234
|
|
|
128
235
|
public credential(profile: LocalProfile): CredentialStore {
|
|
@@ -141,43 +248,180 @@ export class NativeKeyringProfileRegistry implements ProfileRegistry {
|
|
|
141
248
|
);
|
|
142
249
|
}
|
|
143
250
|
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
// Refused before anything is written, so a conflicting or surplus login changes nothing.
|
|
151
|
-
const before = await this.list();
|
|
152
|
-
admitProfile(nextProfileIndex(before, profile, replaces), profile);
|
|
153
|
-
await this.credential(profile).replace(credential);
|
|
251
|
+
protected async proveCredential(): Promise<void> {
|
|
252
|
+
const probe = new NativeNapiKeyringCredentialStore(
|
|
253
|
+
this.#createEntry,
|
|
254
|
+
this.serviceName,
|
|
255
|
+
`probe:${randomUUID()}`,
|
|
256
|
+
);
|
|
154
257
|
try {
|
|
155
|
-
await
|
|
156
|
-
const next = nextProfileIndex(current, profile, replaces);
|
|
157
|
-
admitProfile(next, profile);
|
|
158
|
-
return next;
|
|
159
|
-
});
|
|
258
|
+
await probe.replace(PROBE_CREDENTIAL());
|
|
160
259
|
} catch (error) {
|
|
161
|
-
|
|
162
|
-
// this computer leaves no token behind that no index entry names.
|
|
163
|
-
if (!before.some((saved) => sameLogin(saved, profile)))
|
|
164
|
-
await this.credential(profile).clear();
|
|
260
|
+
await quietly(probe.clear());
|
|
165
261
|
throw error;
|
|
166
262
|
}
|
|
167
|
-
|
|
168
|
-
await this.credential(replaces).clear();
|
|
263
|
+
await probe.clear();
|
|
169
264
|
}
|
|
170
265
|
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
);
|
|
266
|
+
/** The operating system serializes access to one entry; nothing else is coordinated here. */
|
|
267
|
+
public owning<Result>(
|
|
268
|
+
_logins: readonly LoginRef[],
|
|
269
|
+
operation: () => Promise<Result>,
|
|
270
|
+
): Promise<Result> {
|
|
271
|
+
return operation();
|
|
178
272
|
}
|
|
179
273
|
}
|
|
180
274
|
|
|
275
|
+
export interface FileProfileRegistryOptions {
|
|
276
|
+
readonly home?: string;
|
|
277
|
+
readonly indexDirectory?: string;
|
|
278
|
+
readonly ownerId?: number;
|
|
279
|
+
readonly probe?: ProcessProbe;
|
|
280
|
+
/** The longest a process waits to become the owner of a login. */
|
|
281
|
+
readonly waitMs?: number;
|
|
282
|
+
readonly pollMs?: number;
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
/** The provider's request timeout: a process waits no longer than one request for a login. */
|
|
286
|
+
const OWNERSHIP_WAIT_MS = 30_000;
|
|
287
|
+
|
|
288
|
+
/** The logins whose ownership the running async operation already holds, by directory. */
|
|
289
|
+
const heldLogins = new AsyncLocalStorage<ReadonlySet<string>>();
|
|
290
|
+
|
|
291
|
+
/**
|
|
292
|
+
* The login's directory name: its keyring account as one path segment. User and organization IDs
|
|
293
|
+
* contain neither `.` nor `:`, so the mapping cannot make two logins one.
|
|
294
|
+
*/
|
|
295
|
+
const loginKey = (login: LoginRef): string =>
|
|
296
|
+
login === "legacy" ? "legacy" : profileAccount(login).replaceAll(":", ".");
|
|
297
|
+
|
|
298
|
+
/**
|
|
299
|
+
* Tokens in owner-only files below the environment's profile directory, one directory per login.
|
|
300
|
+
* The CLI and the local MCP server use them from separate processes, so every operation that
|
|
301
|
+
* spends a refresh token or changes a login runs as that login's single owner.
|
|
302
|
+
*/
|
|
303
|
+
export class FileProfileRegistry extends IndexedProfileRegistry {
|
|
304
|
+
public readonly kind = "file";
|
|
305
|
+
readonly #root: string;
|
|
306
|
+
readonly #home: string;
|
|
307
|
+
readonly #ancestors: readonly string[];
|
|
308
|
+
readonly #ownerId: number;
|
|
309
|
+
readonly #probe: ProcessProbe;
|
|
310
|
+
readonly #waitMs: number;
|
|
311
|
+
readonly #pollMs: number | undefined;
|
|
312
|
+
|
|
313
|
+
public constructor(serviceName = "ohmyhost", options: FileProfileRegistryOptions = {}) {
|
|
314
|
+
if (!SERVICE_NAME.test(serviceName)) throw new CredentialStoreUnavailableError();
|
|
315
|
+
const home = options.home ?? homedir();
|
|
316
|
+
const indexDirectory = options.indexDirectory ?? profileIndexDirectory(serviceName);
|
|
317
|
+
super(indexDirectory);
|
|
318
|
+
const ownerId = options.ownerId ?? process.getuid?.();
|
|
319
|
+
if (ownerId === undefined) throw new CredentialStoreUnavailableError();
|
|
320
|
+
const anchor = join(home, ".ohmyhost");
|
|
321
|
+
this.#home = home;
|
|
322
|
+
this.#root = join(indexDirectory, "credentials");
|
|
323
|
+
this.#ancestors = indexDirectory.startsWith(anchor + sep)
|
|
324
|
+
? [anchor, ...directoriesBelow(anchor, indexDirectory)]
|
|
325
|
+
: [indexDirectory];
|
|
326
|
+
this.#ownerId = ownerId;
|
|
327
|
+
this.#probe = options.probe ?? linuxProcessProbe();
|
|
328
|
+
this.#waitMs = options.waitMs ?? OWNERSHIP_WAIT_MS;
|
|
329
|
+
this.#pollMs = options.pollMs;
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
public credential(profile: LocalProfile): CredentialStore {
|
|
333
|
+
return this.#storeAt(join(this.#root, loginKey(profile)));
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
public legacy(): CredentialStore {
|
|
337
|
+
return this.#storeAt(join(this.#root, loginKey("legacy")));
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
public async owning<Result>(
|
|
341
|
+
logins: readonly LoginRef[],
|
|
342
|
+
operation: () => Promise<Result>,
|
|
343
|
+
signal?: AbortSignal,
|
|
344
|
+
): Promise<Result> {
|
|
345
|
+
const outer = heldLogins.getStore();
|
|
346
|
+
// A fixed order, so two operations that each need two logins cannot wait for one another.
|
|
347
|
+
const wanted = [...new Set(logins.map((login) => join(this.#root, loginKey(login))))]
|
|
348
|
+
.sort()
|
|
349
|
+
.filter((directory) => outer?.has(directory) !== true);
|
|
350
|
+
if (wanted.length === 0) return await operation();
|
|
351
|
+
const holds: LoginOwnershipHold[] = [];
|
|
352
|
+
try {
|
|
353
|
+
for (const directory of wanted) {
|
|
354
|
+
await this.#storeAt(directory).prepare();
|
|
355
|
+
try {
|
|
356
|
+
holds.push(
|
|
357
|
+
await new LoginOwnership(directory, {
|
|
358
|
+
probe: this.#probe,
|
|
359
|
+
waitMs: this.#waitMs,
|
|
360
|
+
...(this.#pollMs === undefined ? {} : { pollMs: this.#pollMs }),
|
|
361
|
+
}).acquire(signal),
|
|
362
|
+
);
|
|
363
|
+
} catch (error) {
|
|
364
|
+
// The record is named relative to the home directory, the way a refused path is.
|
|
365
|
+
if (error instanceof LoginOwnershipTimeoutError)
|
|
366
|
+
throw new LoginOwnershipTimeoutError(
|
|
367
|
+
relative(this.#home, join(directory, error.record)),
|
|
368
|
+
);
|
|
369
|
+
// An abort ends the wait; any other failure means ownership cannot be taken here at all.
|
|
370
|
+
if (signal?.aborted === true) throw error;
|
|
371
|
+
throw new CredentialStoreUnavailableError();
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
return await heldLogins.run(new Set([...(outer ?? []), ...wanted]), operation);
|
|
375
|
+
} finally {
|
|
376
|
+
for (const hold of holds.reverse()) await hold.release();
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
protected async proveCredential(): Promise<void> {
|
|
381
|
+
const directory = join(this.#root, `probe.${randomUUID()}`);
|
|
382
|
+
const probe = this.#storeAt(directory);
|
|
383
|
+
try {
|
|
384
|
+
await probe.replace(PROBE_CREDENTIAL());
|
|
385
|
+
await probe.clear();
|
|
386
|
+
} finally {
|
|
387
|
+
await quietly(probe.clear());
|
|
388
|
+
await quietly(rmdir(directory));
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
#storeAt(directory: string): OwnerOnlyFileCredentialStore {
|
|
393
|
+
return new OwnerOnlyFileCredentialStore(directory, this.#ownerId, {
|
|
394
|
+
ancestors: this.#ancestors,
|
|
395
|
+
root: this.#root,
|
|
396
|
+
home: this.#home,
|
|
397
|
+
});
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
/** Every directory from just below `anchor` down to `target`, outermost first. */
|
|
402
|
+
const directoriesBelow = (anchor: string, target: string): string[] => {
|
|
403
|
+
const result: string[] = [];
|
|
404
|
+
let current = anchor;
|
|
405
|
+
for (const segment of target.slice(anchor.length).split(sep).filter(Boolean)) {
|
|
406
|
+
current = join(current, segment);
|
|
407
|
+
result.push(current);
|
|
408
|
+
}
|
|
409
|
+
return result;
|
|
410
|
+
};
|
|
411
|
+
|
|
412
|
+
/**
|
|
413
|
+
* The store of this platform: owner-only files on Linux, where a container or a server has no
|
|
414
|
+
* credential store, and the operating system's store everywhere else. The platform alone decides;
|
|
415
|
+
* a failed store call never changes it.
|
|
416
|
+
*/
|
|
417
|
+
export const createProfileRegistry = (
|
|
418
|
+
serviceName: string,
|
|
419
|
+
platform: NodeJS.Platform = process.platform,
|
|
420
|
+
): ProfileRegistry =>
|
|
421
|
+
platform === "linux"
|
|
422
|
+
? new FileProfileRegistry(serviceName)
|
|
423
|
+
: new NativeKeyringProfileRegistry(undefined, serviceName);
|
|
424
|
+
|
|
181
425
|
/**
|
|
182
426
|
* The saved logins as numbered files that are never rewritten. A change reads the newest one and
|
|
183
427
|
* creates the next number through an exclusive hard link, so when two processes change the index at
|
|
@@ -207,6 +451,26 @@ export class ProfileIndexFiles {
|
|
|
207
451
|
throw new CredentialStoreUnavailableError();
|
|
208
452
|
}
|
|
209
453
|
|
|
454
|
+
/**
|
|
455
|
+
* Writes and removes one temporary file beside the index, and links it to a second name the way
|
|
456
|
+
* every index change and every ownership record is made, so a login could be listed and owned.
|
|
457
|
+
*/
|
|
458
|
+
public async probe(): Promise<void> {
|
|
459
|
+
const temporary = join(this.directory, `.index-${randomUUID()}.tmp`);
|
|
460
|
+
const linked = join(this.directory, `.index-${randomUUID()}.tmp`);
|
|
461
|
+
try {
|
|
462
|
+
await mkdir(this.directory, { recursive: true, mode: 0o700 });
|
|
463
|
+
await writeDurably(temporary, "probe");
|
|
464
|
+
await link(temporary, linked);
|
|
465
|
+
await unlink(linked);
|
|
466
|
+
await unlink(temporary);
|
|
467
|
+
} catch {
|
|
468
|
+
await removeTemporary(linked);
|
|
469
|
+
await removeTemporary(temporary);
|
|
470
|
+
throw new CredentialStoreUnavailableError();
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
|
|
210
474
|
/** Applies `change` to the newest index; `undefined` means nothing to change. */
|
|
211
475
|
public async update(
|
|
212
476
|
change: (current: readonly LocalProfile[]) => readonly LocalProfile[] | undefined,
|
|
@@ -707,6 +707,10 @@ export const parseCurrentIdentity = (value: unknown): PublicCurrentIdentity => {
|
|
|
707
707
|
/** The signed-in user and the workspaces it belongs to, as `GET /v1/me/profile` reports them. */
|
|
708
708
|
export interface PublicAccount {
|
|
709
709
|
readonly userId: string;
|
|
710
|
+
/** Whether the provider confirmed the account's email address; a first workspace needs it. */
|
|
711
|
+
readonly emailVerified: boolean;
|
|
712
|
+
/** The public acquisition source recorded for the account, or none for a direct visit. */
|
|
713
|
+
readonly signupSource: string | null;
|
|
710
714
|
readonly organizations: readonly PublicWorkspace[];
|
|
711
715
|
}
|
|
712
716
|
|
|
@@ -726,6 +730,8 @@ export const parseAccountProfile = (value: unknown): PublicAccount => {
|
|
|
726
730
|
const organizationIds = input["organization_ids"];
|
|
727
731
|
if (
|
|
728
732
|
!boundedString(input["user_id"], 1, 128) ||
|
|
733
|
+
typeof input["email_verified"] !== "boolean" ||
|
|
734
|
+
!(input["signup_source"] === null || boundedString(input["signup_source"], 1, 64)) ||
|
|
729
735
|
!Array.isArray(organizations) ||
|
|
730
736
|
!Array.isArray(organizationIds) ||
|
|
731
737
|
organizationIds.some((organizationId) => !isUlid(organizationId)) ||
|
|
@@ -748,7 +754,12 @@ export const parseAccountProfile = (value: unknown): PublicAccount => {
|
|
|
748
754
|
});
|
|
749
755
|
if (new Set(workspaces.map((workspace) => workspace.id)).size !== organizationIds.length)
|
|
750
756
|
throw new ResponseContractError();
|
|
751
|
-
return {
|
|
757
|
+
return {
|
|
758
|
+
userId: input["user_id"] as string,
|
|
759
|
+
emailVerified: input["email_verified"],
|
|
760
|
+
signupSource: input["signup_source"],
|
|
761
|
+
organizations: workspaces,
|
|
762
|
+
};
|
|
752
763
|
};
|
|
753
764
|
|
|
754
765
|
export interface PublicProject {
|
|
@@ -107,35 +107,49 @@ export const selectWorkspace = async (
|
|
|
107
107
|
if (session.profile.organizationId === organization.id) return session.profile;
|
|
108
108
|
if (session.profile.organizationId !== null)
|
|
109
109
|
throw new ProfileOrganizationFixedError(session.profile, organization);
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
const
|
|
113
|
-
|
|
110
|
+
// The refresh token is spent at the provider before anything is saved, so this login and the one
|
|
111
|
+
// it becomes are owned first, in the registry's fixed order; the save below then owns nothing new.
|
|
112
|
+
const becomes: LocalProfile = { ...session.profile, organizationId: organization.id };
|
|
113
|
+
return await session.profiles.owning(
|
|
114
|
+
[session.profile, becomes],
|
|
115
|
+
async () => {
|
|
116
|
+
const stored = await session.store.read();
|
|
117
|
+
if (stored === undefined) throw new InteractiveSessionRequiredError();
|
|
118
|
+
const refreshed = await session.refresher.refresh(
|
|
119
|
+
stored.refreshToken,
|
|
120
|
+
signal,
|
|
121
|
+
organization.workos_id,
|
|
122
|
+
);
|
|
123
|
+
assertVerifiedLogin(
|
|
124
|
+
await identity(refreshed.accessToken),
|
|
125
|
+
session.profile.userId,
|
|
126
|
+
organization.id,
|
|
127
|
+
);
|
|
128
|
+
// That user's existing login in the organization keeps its name; binding under this login's alias
|
|
129
|
+
// would silently rename it for every agent that selects it by name.
|
|
130
|
+
const existing = (await session.profiles.list()).find(
|
|
131
|
+
(saved) =>
|
|
132
|
+
saved.userId === session.profile.userId && saved.organizationId === organization.id,
|
|
133
|
+
);
|
|
134
|
+
const bound: LocalProfile = {
|
|
135
|
+
...session.profile,
|
|
136
|
+
name: existing?.name ?? session.profile.name,
|
|
137
|
+
organizationId: organization.id,
|
|
138
|
+
organizationName: organization.name,
|
|
139
|
+
};
|
|
140
|
+
await session.profiles.save(
|
|
141
|
+
bound,
|
|
142
|
+
{
|
|
143
|
+
...refreshed,
|
|
144
|
+
workosOrganizationId: organization.workos_id,
|
|
145
|
+
organizationId: organization.id,
|
|
146
|
+
},
|
|
147
|
+
session.profile,
|
|
148
|
+
);
|
|
149
|
+
return bound;
|
|
150
|
+
},
|
|
114
151
|
signal,
|
|
115
|
-
organization.workos_id,
|
|
116
152
|
);
|
|
117
|
-
assertVerifiedLogin(
|
|
118
|
-
await identity(refreshed.accessToken),
|
|
119
|
-
session.profile.userId,
|
|
120
|
-
organization.id,
|
|
121
|
-
);
|
|
122
|
-
// That user's existing login in the organization keeps its name; binding under this login's alias
|
|
123
|
-
// would silently rename it for every agent that selects it by name.
|
|
124
|
-
const existing = (await session.profiles.list()).find(
|
|
125
|
-
(saved) => saved.userId === session.profile.userId && saved.organizationId === organization.id,
|
|
126
|
-
);
|
|
127
|
-
const bound: LocalProfile = {
|
|
128
|
-
...session.profile,
|
|
129
|
-
name: existing?.name ?? session.profile.name,
|
|
130
|
-
organizationId: organization.id,
|
|
131
|
-
organizationName: organization.name,
|
|
132
|
-
};
|
|
133
|
-
await session.profiles.save(
|
|
134
|
-
bound,
|
|
135
|
-
{ ...refreshed, workosOrganizationId: organization.workos_id, organizationId: organization.id },
|
|
136
|
-
session.profile,
|
|
137
|
-
);
|
|
138
|
-
return bound;
|
|
139
153
|
};
|
|
140
154
|
|
|
141
155
|
/**
|
|
@@ -30,6 +30,11 @@
|
|
|
30
30
|
"types": "./dist/mcp-source-codec.d.ts",
|
|
31
31
|
"import": "./dist/mcp-source-codec.js"
|
|
32
32
|
},
|
|
33
|
+
"./chat-guidance": {
|
|
34
|
+
"source": "./src/chat-guidance.ts",
|
|
35
|
+
"types": "./dist/chat-guidance.d.ts",
|
|
36
|
+
"import": "./dist/chat-guidance.js"
|
|
37
|
+
},
|
|
33
38
|
"./operation-failure": {
|
|
34
39
|
"source": "./src/operation-failure.ts",
|
|
35
40
|
"types": "./dist/operation-failure.d.ts",
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
type ChatGuidance = { next_step: string; say_to_user?: string };
|
|
2
|
+
type ChatResult = Readonly<Record<string, unknown>>;
|
|
3
|
+
|
|
4
|
+
export const CHAT_MAIN_PATH_INSTRUCTIONS =
|
|
5
|
+
"ohmyho.st hosts the user's app: create a project, save versions of its source, show a private live preview, publish. Main path: project_create, then source_changes to save a version, then preview_open, which returns the project's private preview link; later saves update the preview without a deployment. To show the app, also when continuing an existing project, use preview_open; the Dev site address needs a share link and is not the preview. When ready_to_show is true, give the user that link and ask whether they would like to see it. Publish with deployment_plan and deployment_create when the user asks or agrees; a request that already says deploy, publish or go live is that agreement. Results may carry next_step, written for you, and say_to_user, a plain sentence for the user, to be said in the user's language; the user needs IDs, commits, states and codes only on request. ";
|
|
6
|
+
|
|
7
|
+
export const PREVIEW_OPEN_DESCRIPTION =
|
|
8
|
+
"Open or create the stable private preview of this exact environment and return its link, state and ready_to_show. Source saves update it without a deployment. The link is for the user: hand it over when ready_to_show is true. Private means: keep it out of source files, notes and logs. It has no expiry until rotated.";
|
|
9
|
+
export const PREVIEW_GET_DESCRIPTION =
|
|
10
|
+
"Read the stable private preview of this exact environment: its link, state, saved and applied version, and ready_to_show. The link is for the user: hand it over when ready_to_show is true. Private means: keep it out of source files, notes and logs.";
|
|
11
|
+
|
|
12
|
+
export function previewGuidance(view: ChatResult): ChatGuidance | null {
|
|
13
|
+
if (view["source"] === null)
|
|
14
|
+
return {
|
|
15
|
+
next_step:
|
|
16
|
+
"Nothing is saved in this project yet, so the preview has nothing to show. Save the app with source_changes first; the preview follows the saved version.",
|
|
17
|
+
};
|
|
18
|
+
const url = view["url"];
|
|
19
|
+
if (typeof url !== "string" || !Object.hasOwn(view, "source")) return null;
|
|
20
|
+
if (view["ready_to_show"] === true)
|
|
21
|
+
return {
|
|
22
|
+
next_step:
|
|
23
|
+
"The preview shows the saved version. Give the user this link and ask whether they want to see it. Publish only when the user asks or agrees.",
|
|
24
|
+
say_to_user: `Your app is ready as a private preview: ${url} Do you want to see it?`,
|
|
25
|
+
};
|
|
26
|
+
if (view["status"] === "sleeping")
|
|
27
|
+
return {
|
|
28
|
+
next_step:
|
|
29
|
+
"The preview is paused and starts again when the link is opened. Give the user the link.",
|
|
30
|
+
say_to_user: `Your preview is paused. It starts again when you open the link: ${url}`,
|
|
31
|
+
};
|
|
32
|
+
return {
|
|
33
|
+
next_step:
|
|
34
|
+
"The preview is still starting or applying the saved version, which usually takes under a minute. Read preview_get again in about 10 seconds, for at most 2 minutes, before giving the user the link.",
|
|
35
|
+
say_to_user: "Your preview is starting. This takes up to a minute.",
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export function sourceSaveGuidance(result: ChatResult): ChatGuidance | null {
|
|
40
|
+
if (result["state"] === "succeeded")
|
|
41
|
+
return {
|
|
42
|
+
next_step:
|
|
43
|
+
"The version is saved. Open the preview with preview_open for this project (environment dev on a Paid workspace, prod otherwise) and give the user the link when ready_to_show is true.",
|
|
44
|
+
};
|
|
45
|
+
if (result["state"] === "queued" || result["state"] === "running")
|
|
46
|
+
return {
|
|
47
|
+
next_step:
|
|
48
|
+
"The save is being finished. Read operation_get until it succeeds, then open the preview with preview_open for this project (environment dev on a Paid workspace, prod otherwise).",
|
|
49
|
+
};
|
|
50
|
+
return null;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export function projectCreateGuidance(
|
|
54
|
+
result: ChatResult,
|
|
55
|
+
starterRequested = true,
|
|
56
|
+
): ChatGuidance | null {
|
|
57
|
+
if (result["state"] !== "queued" || typeof result["project_id"] !== "string") return null;
|
|
58
|
+
return {
|
|
59
|
+
next_step: starterRequested
|
|
60
|
+
? "The project exists and its starter files are being prepared, usually in under a minute. Read source_get until the source is ready, then save the app with source_changes using its current commit and generation. Do not initialize the source again."
|
|
61
|
+
: "The project exists. Read operation_get until it succeeds, then read the source binding with source_get. If there is no source, use source_initialize for managed source or source_link for the chosen GitHub repository.",
|
|
62
|
+
say_to_user: "Your project is set up. I am building the first version now.",
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export function deploymentGuidance(result: ChatResult): ChatGuidance | null {
|
|
67
|
+
return result["status"] === "active"
|
|
68
|
+
? {
|
|
69
|
+
next_step:
|
|
70
|
+
"The deployment is online, which does not prove the app works. Open its address and try the app's main action before telling the user it works.",
|
|
71
|
+
}
|
|
72
|
+
: null;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export function withChatGuidance(
|
|
76
|
+
tool: string,
|
|
77
|
+
value: unknown,
|
|
78
|
+
options: { starterRequested?: boolean } = {},
|
|
79
|
+
): unknown {
|
|
80
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) return value;
|
|
81
|
+
const result = value as ChatResult;
|
|
82
|
+
let guidance: ChatGuidance | null;
|
|
83
|
+
switch (tool) {
|
|
84
|
+
case "preview_get":
|
|
85
|
+
case "preview_open":
|
|
86
|
+
guidance = previewGuidance(result);
|
|
87
|
+
break;
|
|
88
|
+
case "source_changes":
|
|
89
|
+
case "source_upload_commit":
|
|
90
|
+
guidance = sourceSaveGuidance(result);
|
|
91
|
+
break;
|
|
92
|
+
case "project_create":
|
|
93
|
+
guidance = projectCreateGuidance(result, options.starterRequested);
|
|
94
|
+
break;
|
|
95
|
+
case "deployment_get":
|
|
96
|
+
guidance = deploymentGuidance(result);
|
|
97
|
+
break;
|
|
98
|
+
default:
|
|
99
|
+
return value;
|
|
100
|
+
}
|
|
101
|
+
return guidance === null ? value : { ...guidance, ...result };
|
|
102
|
+
}
|
|
@@ -6,6 +6,8 @@ export interface PreviewView {
|
|
|
6
6
|
readonly status: "cold" | "starting" | "ready" | "sleeping";
|
|
7
7
|
readonly url: string;
|
|
8
8
|
readonly source: Readonly<{ sequence: number; commit_sha: string }> | null;
|
|
9
|
+
readonly applied_source: PreviewView["source"];
|
|
10
|
+
readonly ready_to_show: boolean;
|
|
9
11
|
}
|
|
10
12
|
|
|
11
13
|
export function parsePreviewView(
|
|
@@ -17,21 +19,23 @@ export function parsePreviewView(
|
|
|
17
19
|
const row = value as Record<string, unknown>;
|
|
18
20
|
const ulid = /^[0-7][0-9A-HJKMNP-TV-Z]{25}$/u;
|
|
19
21
|
if (
|
|
20
|
-
Object.keys(row).sort().join(",") !==
|
|
22
|
+
Object.keys(row).sort().join(",") !==
|
|
23
|
+
"applied_source,environment,id,project_id,ready_to_show,source,status,url" ||
|
|
21
24
|
typeof row["id"] !== "string" ||
|
|
22
25
|
!ulid.test(row["id"]) ||
|
|
23
26
|
typeof row["project_id"] !== "string" ||
|
|
24
27
|
!ulid.test(row["project_id"]) ||
|
|
25
28
|
(row["environment"] !== "dev" && row["environment"] !== "prod") ||
|
|
26
29
|
!["cold", "starting", "ready", "sleeping"].includes(String(row["status"])) ||
|
|
30
|
+
typeof row["ready_to_show"] !== "boolean" ||
|
|
27
31
|
typeof row["url"] !== "string" ||
|
|
28
32
|
!/^https:\/\/[a-z2-7]{51}[aq]\.preview(?:\.dev)?\.omh\.st$/u.test(row["url"]) ||
|
|
29
33
|
(scope !== undefined &&
|
|
30
34
|
(row["project_id"] !== scope.projectId || row["environment"] !== scope.environment))
|
|
31
35
|
)
|
|
32
36
|
throw new TypeError("Invalid preview response");
|
|
33
|
-
|
|
34
|
-
|
|
37
|
+
for (const source of [row["source"], row["applied_source"]]) {
|
|
38
|
+
if (source === null) continue;
|
|
35
39
|
if (!source || typeof source !== "object" || Array.isArray(source))
|
|
36
40
|
throw new TypeError("Invalid preview response");
|
|
37
41
|
const item = source as Record<string, unknown>;
|