dsh-workbuddy-bridge 0.1.0

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/lib/bin.js ADDED
@@ -0,0 +1,237 @@
1
+ #!/usr/bin/env node
2
+ import { D as cnAppDiscovery, E as WorkBuddyAtRestKeyProvider, O as WorkBuddyUpstreamClient, X as resolveAppVersion, b as WorkBuddyCredentialStore, f as WORKBUDDY_BRIDGE_VERSION, g as FALLBACK_WORKBUDDY_MODELS, h as FALLBACK_WORKBUDDY_AI_MODELS, i as variantFor, l as readHostHeartbeat, n as CN_VARIANT, r as WORKBUDDY_VARIANTS, s as isHeartbeatProcessAlive, u as workbuddyHostHeartbeatPath } from "./variants-CFO_LIBm.js";
3
+ import { realpathSync } from "node:fs";
4
+ import { fileURLToPath } from "node:url";
5
+ //#region src/cli/bin.ts
6
+ /** Standalone status/diagnostics CLI for the dsh-workbuddy-bridge bundle. */
7
+ const JSON_SCHEMA_VERSION = 1;
8
+ /** Remove token-like strings from an unexpected diagnostic message. */
9
+ function safeMessage(error) {
10
+ return (error instanceof Error ? error.message : String(error)).replace(/\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b/gu, "[redacted token]").replace(/(\b(?:code|token|refresh_token|access_token)=)[^&\s]+/giu, "$1[redacted]");
11
+ }
12
+ function printHelp() {
13
+ process.stdout.write([
14
+ "Usage: dsh-workbuddy-bridge <doctor|status|logout> [--provider <id>] [--json]",
15
+ "",
16
+ " doctor secret-free sign-in and environment diagnostics",
17
+ " status sign-in state, remaining WorkBuddy credit, and host-bundle health",
18
+ " logout remove the plugin-owned credential copy (the desktop app keeps its sign-in)",
19
+ "",
20
+ " --provider which product to inspect; defaults to workbuddy",
21
+ ` one of: ${WORKBUDDY_VARIANTS.map((variant) => variant.id).join(", ")}`,
22
+ " --json emit one secret-free JSON document (doctor/status only)",
23
+ ""
24
+ ].join("\n"));
25
+ }
26
+ function printJson(value) {
27
+ process.stdout.write(`${JSON.stringify(value)}\n`);
28
+ }
29
+ /**
30
+ * One variant's store plus the client that performs its refreshes.
31
+ *
32
+ * The key provider is injected explicitly, and per variant, for the same
33
+ * reason the plugin host does it: the provider must not be left to its no-arg
34
+ * default — that default is deliberately `discovery: 'none'`, and relying on it
35
+ * here would quietly strip the CN CLI of the decryption it has always had.
36
+ */
37
+ function makeStore(variant) {
38
+ const client = new WorkBuddyUpstreamClient();
39
+ return new WorkBuddyCredentialStore({
40
+ variant,
41
+ refresh: (credential) => client.refreshToken(credential),
42
+ keyProvider: new WorkBuddyAtRestKeyProvider({ discovery: variant.id === CN_VARIANT.id ? cnAppDiscovery() : "none" })
43
+ });
44
+ }
45
+ /** The plugin-owned credential copy for one variant, for display. */
46
+ function ownAuthPath(variant) {
47
+ return makeStore(variant).ownAuthPath();
48
+ }
49
+ /** Fallback roster size for one variant. */
50
+ function fallbackCount(variant) {
51
+ return variant.id === CN_VARIANT.id ? FALLBACK_WORKBUDDY_MODELS.length : FALLBACK_WORKBUDDY_AI_MODELS.length;
52
+ }
53
+ async function doctor(jsonOutput, variant) {
54
+ const store = makeStore(variant);
55
+ const status = await store.status();
56
+ const desktopPresent = await store.desktopFilePresent();
57
+ const desktopFormat = await store.desktopAuthFormat();
58
+ const desktopPath = await store.resolvedDesktopAuthPath() ?? store.desktopAuthPath();
59
+ const heartbeat = await readHostHeartbeat();
60
+ const hostAlive = heartbeat !== void 0 && isHeartbeatProcessAlive(heartbeat);
61
+ const appVersion = variant.region === "global" ? await resolveAppVersion() : void 0;
62
+ const decryptionNote = status.state === "signed-out" && desktopFormat === "encrypted" && status.reason !== void 0 ? `Encrypted desktop credential could not be used: ${status.reason}` : void 0;
63
+ const report = {
64
+ schemaVersion: JSON_SCHEMA_VERSION,
65
+ package: "dsh-workbuddy-bridge",
66
+ version: WORKBUDDY_BRIDGE_VERSION,
67
+ node: process.version,
68
+ provider: variant.id,
69
+ displayName: variant.displayName,
70
+ desktopAuthFile: {
71
+ path: desktopPath ?? `(no platform default; set ${variant.env})`,
72
+ present: desktopPresent,
73
+ format: desktopFormat
74
+ },
75
+ ownAuthFile: ownAuthPath(variant),
76
+ ...appVersion === void 0 ? {} : { catalogUserAgent: {
77
+ version: appVersion.version,
78
+ source: appVersion.source,
79
+ ...appVersion.bundle === void 0 ? {} : { bundle: appVersion.bundle }
80
+ } },
81
+ hostHeartbeat: {
82
+ path: workbuddyHostHeartbeatPath(),
83
+ present: heartbeat !== void 0,
84
+ ...heartbeat === void 0 ? {} : {
85
+ registeredAt: heartbeat.registeredAt,
86
+ pid: heartbeat.pid
87
+ },
88
+ processAlive: hostAlive
89
+ },
90
+ signIn: status.state,
91
+ fallbackModels: fallbackCount(variant),
92
+ hints: [
93
+ ...decryptionNote !== void 0 ? [decryptionNote] : status.state === "signed-out" ? [`Sign in once in the ${variant.appName} desktop app, then run status again.`] : [],
94
+ ...desktopPresent ? [] : [`No ${variant.appName} desktop auth file at the expected path; set ${variant.env} if it lives elsewhere.`],
95
+ ...hostAlive ? [] : ["Host bundle not running in this DSH profile (or the process exited). The browser card and provider are unavailable until DSH starts the plugin."]
96
+ ]
97
+ };
98
+ if (jsonOutput) printJson({
99
+ ...report,
100
+ ...decryptionNote === void 0 ? {} : { decryptionNote }
101
+ });
102
+ else process.stdout.write([
103
+ `${variant.displayName} Connect ${WORKBUDDY_BRIDGE_VERSION} on ${process.version}`,
104
+ `Desktop auth file: ${report.desktopAuthFile.present ? "present" : "missing"} — ${desktopFormat} (${report.desktopAuthFile.path})`,
105
+ `Host bundle: ${hostAlive ? `running (pid ${heartbeat.pid})` : heartbeat !== void 0 ? "stale heartbeat (process exited)" : "not started"}`,
106
+ `Sign-in state: ${report.signIn}`,
107
+ `Static fallback models: ${report.fallbackModels}`,
108
+ ...appVersion === void 0 ? [] : [`Catalog User-Agent version: ${appVersion.version} (${appVersion.source})`],
109
+ ...report.hints.map((hint) => `Hint: ${hint}`),
110
+ ""
111
+ ].join("\n"));
112
+ return status.state === "signed-in" && desktopPresent ? 0 : 1;
113
+ }
114
+ async function status(jsonOutput, variant) {
115
+ const store = makeStore(variant);
116
+ const client = new WorkBuddyUpstreamClient();
117
+ const authStatus = await store.status();
118
+ const heartbeat = await readHostHeartbeat();
119
+ const hostAlive = heartbeat !== void 0 && isHeartbeatProcessAlive(heartbeat);
120
+ const hostState = hostAlive ? "running" : heartbeat !== void 0 ? "stale" : "not-started";
121
+ if (authStatus.state !== "signed-in") {
122
+ if (jsonOutput) printJson({
123
+ schemaVersion: JSON_SCHEMA_VERSION,
124
+ package: "dsh-workbuddy-bridge",
125
+ version: WORKBUDDY_BRIDGE_VERSION,
126
+ provider: variant.id,
127
+ status: "signed-out",
128
+ hostBundle: hostState
129
+ });
130
+ else process.stdout.write(`${variant.displayName} Connect: signed out\nHost bundle: ${hostState}\n`);
131
+ return 1;
132
+ }
133
+ let credits;
134
+ try {
135
+ const credential = await store.current();
136
+ if (credential !== void 0) {
137
+ const fetched = await client.fetchCredits(credential);
138
+ credits = {
139
+ total: fetched.total,
140
+ ...fetched.unlimited === true ? { unlimited: true } : {}
141
+ };
142
+ }
143
+ } catch (error) {
144
+ credits = {
145
+ total: 0,
146
+ error: safeMessage(error)
147
+ };
148
+ }
149
+ const expiresAt = authStatus.expiresAtMs !== void 0 ? new Date(authStatus.expiresAtMs).toISOString() : void 0;
150
+ if (jsonOutput) {
151
+ printJson({
152
+ schemaVersion: JSON_SCHEMA_VERSION,
153
+ package: "dsh-workbuddy-bridge",
154
+ version: WORKBUDDY_BRIDGE_VERSION,
155
+ provider: variant.id,
156
+ status: "signed-in",
157
+ ...expiresAt === void 0 ? {} : { accessTokenExpires: expiresAt },
158
+ ...authStatus.nickname === void 0 ? {} : { nickname: authStatus.nickname },
159
+ ...authStatus.domain === void 0 || authStatus.domain === "" ? {} : { domain: authStatus.domain },
160
+ source: authStatus.source,
161
+ credits: credits?.total,
162
+ ...credits?.unlimited === true ? { creditsUnlimited: true } : {},
163
+ ...credits?.error === void 0 ? {} : { creditsError: credits.error },
164
+ hostBundle: hostState
165
+ });
166
+ return 0;
167
+ }
168
+ process.stdout.write([
169
+ `${variant.displayName} Connect: signed in${authStatus.nickname === void 0 ? "" : ` as ${authStatus.nickname}`}`,
170
+ ...expiresAt === void 0 ? [] : [`Access token expires ${expiresAt} (refresh is automatic)`],
171
+ credits?.error !== void 0 ? `Remaining credit: unavailable (${credits.error})` : credits?.unlimited === true ? "Remaining credit: unlimited" : `Remaining credit: ${credits?.total ?? "unknown"}`,
172
+ `Host bundle: ${hostAlive ? `running (pid ${heartbeat.pid})` : hostState === "stale" ? "stale heartbeat (DSH process exited)" : "not started in this profile"}`,
173
+ "Client card: load failures are logged to the browser console only; the host provider is unaffected.",
174
+ ""
175
+ ].join("\n"));
176
+ return 0;
177
+ }
178
+ /** Execute one boot-free command. */
179
+ async function run(argv) {
180
+ if (argv.length === 0 || argv[0] === "--help" || argv[0] === "-h") {
181
+ printHelp();
182
+ return 0;
183
+ }
184
+ const [rawAction, ...flags] = argv;
185
+ if (![
186
+ "doctor",
187
+ "logout",
188
+ "status"
189
+ ].includes(rawAction)) {
190
+ process.stderr.write(`dsh-workbuddy-bridge: expected doctor, logout, or status; got ${JSON.stringify(rawAction)}\n`);
191
+ return 1;
192
+ }
193
+ const action = rawAction;
194
+ const jsonOutput = flags.includes("--json");
195
+ let providerId;
196
+ const rest = [];
197
+ for (let index = 0; index < flags.length; index += 1) {
198
+ const flag = flags[index];
199
+ if (flag === "--provider") {
200
+ providerId = flags[index + 1];
201
+ index += 1;
202
+ continue;
203
+ }
204
+ if (flag.startsWith("--provider=")) {
205
+ providerId = flag.slice(11);
206
+ continue;
207
+ }
208
+ rest.push(flag);
209
+ }
210
+ const variant = providerId === void 0 ? CN_VARIANT : variantFor(providerId);
211
+ if (variant === void 0) {
212
+ process.stderr.write(`dsh-workbuddy-bridge: unknown provider ${JSON.stringify(providerId)}; expected one of ${WORKBUDDY_VARIANTS.map((v) => v.id).join(", ")}\n`);
213
+ return 1;
214
+ }
215
+ if (rest.filter((flag) => flag !== "--json").length > 0 || jsonOutput && action === "logout") {
216
+ process.stderr.write(`dsh-workbuddy-bridge: invalid options for ${action}: ${flags.join(" ")}\n`);
217
+ return 1;
218
+ }
219
+ try {
220
+ switch (action) {
221
+ case "doctor": return await doctor(jsonOutput, variant);
222
+ case "status": return await status(jsonOutput, variant);
223
+ case "logout": {
224
+ const store = makeStore(variant);
225
+ await store.logout();
226
+ process.stdout.write(`${variant.displayName} Connect: removed ${store.ownAuthPath()}; the desktop app's sign-in is untouched\n`);
227
+ return 0;
228
+ }
229
+ }
230
+ } catch (error) {
231
+ process.stderr.write(`dsh-workbuddy-bridge: ${action} failed: ${safeMessage(error)}\n`);
232
+ return 1;
233
+ }
234
+ }
235
+ if (process.argv[1] !== void 0 && fileURLToPath(import.meta.url) === realpathSync(process.argv[1])) process.exitCode = await run(process.argv.slice(2));
236
+ //#endregion
237
+ export { run };