@enhance-eng/enhance 0.1.3 → 0.1.5

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 (2) hide show
  1. package/dist/main.mjs +319 -46
  2. package/package.json +3 -1
package/dist/main.mjs CHANGED
@@ -2,15 +2,17 @@
2
2
  import { Command } from "commander";
3
3
  import { FailedToExitError, createCli, parseRouter } from "trpc-cli";
4
4
  import { z } from "zod";
5
- import { setTimeout } from "node:timers/promises";
5
+ import { setTimeout as setTimeout$1 } from "node:timers/promises";
6
+ import { homedir, hostname, tmpdir } from "node:os";
6
7
  import process from "node:process";
7
8
  import { createInterface } from "node:readline";
8
9
  import { chmodSync, createReadStream, createWriteStream, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, statSync, unlinkSync, writeFileSync } from "node:fs";
9
10
  import path from "node:path";
10
11
  import { TRPCClientError, createTRPCUntypedClient, httpLink } from "@trpc/client";
11
- import { createHash, randomUUID } from "node:crypto";
12
+ import { createHash, randomBytes, randomUUID } from "node:crypto";
12
13
  import { chmod, mkdir, mkdtemp, readFile, realpath, rename, rm, stat, unlink, writeFile } from "node:fs/promises";
13
- import { homedir, tmpdir } from "node:os";
14
+ import { spawn } from "node:child_process";
15
+ import { createServer } from "node:http";
14
16
  import { Readable, Transform } from "node:stream";
15
17
  import { pipeline } from "node:stream/promises";
16
18
  import { ZipFile } from "yazl";
@@ -95,6 +97,7 @@ const viewerCapabilitySchema = z.object({
95
97
  "sign-in",
96
98
  "no"
97
99
  ]),
100
+ share: z.boolean(),
98
101
  manage: z.boolean()
99
102
  });
100
103
  const canvasSchema = z.object({
@@ -188,10 +191,10 @@ const restoreCanvasInputSchema = z.object({ canvasId: z.uuid() });
188
191
  const restoreCanvasOutputSchema = z.object({ canvasId: z.uuid() });
189
192
  //#endregion
190
193
  //#region ../../packages/contract/src/canvas/canvas-presentation.schema.ts
191
- const MAX_ABSOLUTE_VALUE$1 = 1e5;
194
+ const MAX_CANVAS_VALUE = 1e5;
192
195
  const MAX_ITEM_ID_LENGTH$1 = 200;
193
- const boundedNumber$1 = z.number().min(-1e5).max(MAX_ABSOLUTE_VALUE$1);
194
- const nonNegativeNumber$1 = z.number().nonnegative().max(MAX_ABSOLUTE_VALUE$1);
196
+ const boundedNumber$1 = z.number().min(-1e5).max(MAX_CANVAS_VALUE);
197
+ const nonNegativeNumber$1 = z.number().nonnegative().max(MAX_CANVAS_VALUE);
195
198
  const ratio = z.number().min(0).max(1);
196
199
  const itemId = z.string().min(1).max(MAX_ITEM_ID_LENGTH$1);
197
200
  const canvasColorSchema = z.object({
@@ -340,6 +343,7 @@ const canvasBlendModeSchema = z.enum([
340
343
  "overlay",
341
344
  "darken",
342
345
  "lighten",
346
+ "plus-lighter",
343
347
  "color-dodge",
344
348
  "color-burn",
345
349
  "hard-light",
@@ -451,7 +455,7 @@ const canvasNodeLayoutSchema = z.object({
451
455
  flipHorizontal: z.boolean().optional(),
452
456
  flipVertical: z.boolean().optional(),
453
457
  aspectRatioLocked: z.boolean().optional(),
454
- aspectRatio: z.number().positive().max(MAX_ABSOLUTE_VALUE$1).optional(),
458
+ aspectRatio: z.number().positive().max(MAX_CANVAS_VALUE).optional(),
455
459
  horizontal: canvasSizeIntentSchema,
456
460
  vertical: canvasSizeIntentSchema,
457
461
  position: z.enum(["flow", "absolute"]),
@@ -469,20 +473,16 @@ const canvasNodeLayoutSchema = z.object({
469
473
  clipContent: z.boolean().optional(),
470
474
  container: canvasFlexLayoutSchema.optional()
471
475
  });
472
- //#endregion
473
- //#region ../../packages/contract/src/canvas/canvas-content-styles.schema.ts
474
- const MAX_ABSOLUTE_VALUE = 1e5;
475
- const MAX_FONT_WEIGHT = 1e3;
476
+ const MAX_CANVAS_FONT_WEIGHT = 1e3;
476
477
  const MAX_ITEM_ID_LENGTH = 200;
477
- const MAX_ASSET_ID_LENGTH = 500;
478
- const MAX_STYLE_VALUE_LENGTH = 1e4;
479
- const boundedNumber = z.number().min(-1e5).max(MAX_ABSOLUTE_VALUE);
480
- const nonNegativeNumber = z.number().nonnegative().max(MAX_ABSOLUTE_VALUE);
478
+ const MAX_CANVAS_ADDITIONAL_STYLE_VALUE_LENGTH = 1e4;
479
+ const boundedNumber = z.number().min(-1e5).max(MAX_CANVAS_VALUE);
480
+ const nonNegativeNumber = z.number().nonnegative().max(MAX_CANVAS_VALUE);
481
481
  const canvasTypographySchema = z.object({
482
- family: z.string().min(1).max(MAX_ASSET_ID_LENGTH),
483
- fallbackFamilies: z.array(z.string().min(1).max(MAX_ASSET_ID_LENGTH)).max(20),
482
+ family: z.string().min(1).max(500),
483
+ fallbackFamilies: z.array(z.string().min(1).max(500)).max(20),
484
484
  size: nonNegativeNumber,
485
- weight: z.number().int().min(1).max(MAX_FONT_WEIGHT),
485
+ weight: z.number().int().min(1).max(MAX_CANVAS_FONT_WEIGHT),
486
486
  style: z.enum([
487
487
  "normal",
488
488
  "italic",
@@ -542,7 +542,7 @@ const canvasTypographySchema = z.object({
542
542
  const unsafeStyleValue = /javascript|vbscript|data\s*:\s*text\/html|expression\s*\(|@import/iu;
543
543
  const blockedStyleProperty = /^(?:behavior|-moz-binding)$/iu;
544
544
  const canvasAdditionalStylePropertySchema = z.string().min(1).max(MAX_ITEM_ID_LENGTH).regex(/^(?:--[\w-]+|[a-z][a-z\d-]*)$/iu).refine((property) => !blockedStyleProperty.test(property), "unsafe CSS property");
545
- const canvasAdditionalStyleValueSchema = z.string().max(MAX_STYLE_VALUE_LENGTH).refine((value) => !unsafeStyleValue.test(value), "unsafe CSS value");
545
+ const canvasAdditionalStyleValueSchema = z.string().max(MAX_CANVAS_ADDITIONAL_STYLE_VALUE_LENGTH).refine((value) => !unsafeStyleValue.test(value), "unsafe CSS value");
546
546
  const canvasAdditionalStyleSchema = z.object({
547
547
  id: z.string().min(1).max(MAX_ITEM_ID_LENGTH),
548
548
  property: canvasAdditionalStylePropertySchema,
@@ -860,8 +860,8 @@ const emptyCanvasSceneDocument = () => ({
860
860
  });
861
861
  //#endregion
862
862
  //#region ../../packages/contract/src/canvas/canvas-conversion.schema.ts
863
- const MAX_CANVAS_CONVERSION_NODES = 2500;
864
- const MAX_CANVAS_CONVERSION_SOURCE_NODES = 5e3;
863
+ const MAX_CANVAS_CONVERSION_NODES = 3e4;
864
+ const MAX_CANVAS_CONVERSION_SOURCE_NODES = 5e4;
865
865
  const MAX_CANVAS_HTML_SOURCE_LENGTH = 262144;
866
866
  const MAX_CANVAS_ID_PREFIX_LENGTH = 80;
867
867
  const temporaryIdSchema = z.string().min(1).max(200);
@@ -1749,7 +1749,8 @@ const canvasPresencePatchSchema = z.object({
1749
1749
  focused: z.boolean().optional(),
1750
1750
  selectedNodeIds: z.array(z.string().min(1).max(MAX_NODE_ID_LENGTH$1)).max(MAX_SELECTION_SIZE).optional(),
1751
1751
  visibleWorldBox: visibleWorldBoxSchema.optional(),
1752
- gesture: gesturePreviewSchema.nullable().optional()
1752
+ gesture: gesturePreviewSchema.nullable().optional(),
1753
+ cursorChat: z.string().max(140).nullable().optional()
1753
1754
  }).refine((patch) => Object.keys(patch).length > 0, "presence patch cannot be empty");
1754
1755
  const canvasPresenceSchema = z.object({
1755
1756
  actor: canvasRoomActorSchema,
@@ -1764,6 +1765,7 @@ const canvasPresenceSchema = z.object({
1764
1765
  selectedNodeIds: z.array(z.string().min(1).max(MAX_NODE_ID_LENGTH$1)).max(MAX_SELECTION_SIZE),
1765
1766
  visibleWorldBox: visibleWorldBoxSchema.nullable(),
1766
1767
  gesture: gesturePreviewSchema.nullable(),
1768
+ cursorChat: z.string().max(140).nullable().default(null),
1767
1769
  expiresAt: z.iso.datetime()
1768
1770
  });
1769
1771
  const canvasAgentActivityPhaseSchema = z.enum([
@@ -2305,6 +2307,16 @@ const commentAuthorSchema = z.object({
2305
2307
  /** Non-null only for an agent. An attribution product may not let a machine pass as one. */
2306
2308
  tokenLabel: z.string().max(120).nullable()
2307
2309
  });
2310
+ const commentMentionSchema = z.object({
2311
+ personId: z.uuid(),
2312
+ name: z.string().min(1).max(120)
2313
+ });
2314
+ const MAX_REACTION_EMOJI_LENGTH = 16;
2315
+ const MAX_MENTIONS_PER_MESSAGE = 10;
2316
+ const commentReactionSchema = z.object({
2317
+ emoji: z.string().min(1).max(MAX_REACTION_EMOJI_LENGTH),
2318
+ people: z.array(commentMentionSchema).min(1)
2319
+ });
2308
2320
  const commentMessageSchema = z.object({
2309
2321
  messageId: z.uuid(),
2310
2322
  seq: z.number().int().min(1),
@@ -2312,7 +2324,9 @@ const commentMessageSchema = z.object({
2312
2324
  author: commentAuthorSchema,
2313
2325
  createdAt: z.iso.datetime(),
2314
2326
  /** A comment that changed after somebody read it should say so. */
2315
- editedAt: z.iso.datetime().nullable()
2327
+ editedAt: z.iso.datetime().nullable(),
2328
+ mentions: z.array(commentMentionSchema),
2329
+ reactions: z.array(commentReactionSchema)
2316
2330
  });
2317
2331
  const commentResolverSchema = z.object({
2318
2332
  kind: z.enum(["person", "agent"]),
@@ -2355,19 +2369,30 @@ const startCommentInputSchema = z.object({
2355
2369
  */
2356
2370
  clientThreadId: z.uuid(),
2357
2371
  anchor: commentAnchorSchema,
2358
- body: z.string().trim().min(1).max(MAX_BODY_LENGTH)
2372
+ body: z.string().trim().min(1).max(MAX_BODY_LENGTH),
2373
+ mentionedPersonIds: z.array(z.uuid()).max(MAX_MENTIONS_PER_MESSAGE).default([])
2359
2374
  });
2360
2375
  const replyCommentInputSchema = z.object({
2361
2376
  canvasId: z.uuid(),
2362
2377
  threadId: z.uuid(),
2363
2378
  clientMessageId: z.uuid(),
2364
- body: z.string().trim().min(1).max(MAX_BODY_LENGTH)
2379
+ body: z.string().trim().min(1).max(MAX_BODY_LENGTH),
2380
+ mentionedPersonIds: z.array(z.uuid()).max(MAX_MENTIONS_PER_MESSAGE).default([])
2365
2381
  });
2366
2382
  const editCommentInputSchema = z.object({
2367
2383
  canvasId: z.uuid(),
2368
2384
  threadId: z.uuid(),
2369
2385
  messageId: z.uuid(),
2370
- body: z.string().trim().min(1).max(MAX_BODY_LENGTH)
2386
+ body: z.string().trim().min(1).max(MAX_BODY_LENGTH),
2387
+ mentionedPersonIds: z.array(z.uuid()).max(MAX_MENTIONS_PER_MESSAGE).default([])
2388
+ });
2389
+ /** A target state, so a retried click cannot invert somebody's reaction. */
2390
+ const reactToCommentInputSchema = z.object({
2391
+ canvasId: z.uuid(),
2392
+ threadId: z.uuid(),
2393
+ messageId: z.uuid(),
2394
+ emoji: z.string().trim().min(1).max(MAX_REACTION_EMOJI_LENGTH),
2395
+ reacted: z.boolean()
2371
2396
  });
2372
2397
  const moveCommentInputSchema = z.object({
2373
2398
  canvasId: z.uuid(),
@@ -2577,6 +2602,12 @@ const revokeAgentTokenOutputSchema = z.object({
2577
2602
  tokenId: z.uuid(),
2578
2603
  revoked: z.literal(true)
2579
2604
  });
2605
+ const cliAuthConfigurationSchema = z.discriminatedUnion("method", [z.object({ method: z.literal("token") }), z.object({
2606
+ method: z.literal("browser"),
2607
+ issuer: z.url(),
2608
+ clientId: z.string().min(1),
2609
+ scope: z.literal("openid")
2610
+ })]);
2580
2611
  //#endregion
2581
2612
  //#region ../../packages/contract/src/person/person.schema.ts
2582
2613
  const personSchema = z.object({
@@ -3755,7 +3786,7 @@ var CliError = class extends Error {
3755
3786
  const TOKEN = /^enh_[\w-]{43}$/;
3756
3787
  const authenticated = (value) => {
3757
3788
  const parsed = getMeOutputSchema.parse(value);
3758
- if (parsed.authentication.kind !== "agent" || parsed.person === null) throw new CliError("UNAUTHORIZED", "The credential is missing, expired, revoked, or invalid.", "A human must copy the canvas's Connect Agent prompt, then run 'enhance auth login'.");
3789
+ if (parsed.authentication.kind !== "agent" || parsed.person === null) throw new CliError("UNAUTHORIZED", "The credential is missing, expired, revoked, or invalid.", "Run 'enhance auth login' and complete authentication in the browser.");
3759
3790
  return {
3760
3791
  authenticated: true,
3761
3792
  personId: parsed.person.id,
@@ -3765,13 +3796,31 @@ const authenticated = (value) => {
3765
3796
  expiresAt: parsed.authentication.expiresAt
3766
3797
  };
3767
3798
  };
3768
- const createAuthUseCase = (credentials, remote) => ({
3769
- login: async (token) => {
3770
- if (!TOKEN.test(token)) throw new CliError("BAD_REQUEST", "Agent tokens begin with enh_ and contain 32 base64url bytes.", "Pass the token from the canvas's Connect Agent prompt to 'enhance auth login' through stdin.");
3799
+ const createAuthUseCase = (credentials, remote, browser) => ({
3800
+ loginWithToken: async (token) => {
3801
+ if (!TOKEN.test(token)) throw new CliError("BAD_REQUEST", "Agent tokens begin with enh_ and contain 32 base64url bytes.", "Pass a manual token from Settings to 'enhance auth login' through stdin.");
3771
3802
  const status = authenticated(await remote.queryWithToken("person.me", {}, token));
3772
3803
  await credentials.write(token);
3773
3804
  return status;
3774
3805
  },
3806
+ loginWithBrowser: async (input) => {
3807
+ const configuration = cliAuthConfigurationSchema.parse(await remote.authenticationConfig());
3808
+ if (configuration.method === "token") throw new CliError("BAD_REQUEST", "Browser authentication is not configured for this Enhance environment.", "Ask an administrator to configure CLI OAuth, or pass an agent token to 'enhance auth login --token'.");
3809
+ const accessToken = await browser.authorize({
3810
+ issuer: configuration.issuer,
3811
+ clientId: configuration.clientId,
3812
+ scope: configuration.scope,
3813
+ openBrowser: input.openBrowser,
3814
+ onReady: input.onReady
3815
+ });
3816
+ const created = createAgentTokenOutputSchema.parse(await remote.mutateWithToken("person.createAgentToken", {
3817
+ label: input.label,
3818
+ expiresAt: null
3819
+ }, accessToken));
3820
+ const status = authenticated(await remote.queryWithToken("person.me", {}, created.token));
3821
+ await credentials.write(created.token);
3822
+ return status;
3823
+ },
3775
3824
  status: async () => {
3776
3825
  if (await credentials.read() === null) throw new CliError("UNAUTHORIZED", `No credential exists at ${credentials.path}.`, "A human must run 'enhance auth login'.");
3777
3826
  return authenticated(await remote.query("person.me", {}));
@@ -3807,7 +3856,7 @@ const waitUntilSettled = async (remote, input) => {
3807
3856
  if (!parsed.success) throw invalidResponse$2("status");
3808
3857
  if (parsed.data.state === "ready" || parsed.data.state === "failed") return parsed.data;
3809
3858
  if (parsed.data.state === "abandoned") throw new CliError("NOT_FOUND", `Prototype deployment ${input.deploymentId} was abandoned.`, "Publish the directory again with a new client token.");
3810
- await setTimeout(pollMs);
3859
+ await setTimeout$1(pollMs);
3811
3860
  pollMs = Math.min(pollMs * 2, MAX_POLL_MS);
3812
3861
  }
3813
3862
  throw new Error("prototype ingestion is still running");
@@ -4042,12 +4091,41 @@ const readToken = async (offered, command) => {
4042
4091
  }
4043
4092
  throw new CliError("BAD_REQUEST", "A token is required.", `Pass '--token <token>' or pipe one line to '${command}'.`);
4044
4093
  };
4094
+ const readOptionalToken = async (offered) => {
4095
+ if (offered !== void 0) return offered.trim();
4096
+ if (process.stdin.isTTY) return null;
4097
+ const lines = createInterface({
4098
+ input: process.stdin,
4099
+ crlfDelay: Infinity
4100
+ });
4101
+ for await (const line of lines) {
4102
+ lines.close();
4103
+ const piped = line.trim();
4104
+ return piped === "" ? null : piped;
4105
+ }
4106
+ return null;
4107
+ };
4045
4108
  //#endregion
4046
4109
  //#region src/infrastructure/auth.program.ts
4110
+ const MAX_TOKEN_LABEL_CHARACTERS = 120;
4047
4111
  const registerAuthProgram = (program, auth, output) => {
4048
4112
  const command = program.command("auth").description("Store and inspect the agent credential.");
4049
- command.command("login").description("Validate an agent token, then store it in the protected credential file.").option("--token <token>", "Token from Connect Agent. Omit it to read one line from stdin.").action(async (options) => {
4050
- output.result(await auth.login(await readToken(options.token, "enhance auth login")));
4113
+ command.command("login").description("Authenticate in a browser, then store a revocable agent credential.").option("--token <token>", "Use an existing agent token instead of browser authentication.").option("--no-open", "Print the authorization URL without opening the browser.").action(async (options) => {
4114
+ const token = await readOptionalToken(options.token);
4115
+ if (token !== null) {
4116
+ output.result(await auth.loginWithToken(token));
4117
+ return;
4118
+ }
4119
+ output.result(await auth.loginWithBrowser({
4120
+ label: `CLI on ${hostname()}`.slice(0, MAX_TOKEN_LABEL_CHARACTERS),
4121
+ openBrowser: options.open,
4122
+ onReady: (url) => {
4123
+ output.result({
4124
+ status: "waiting_for_browser",
4125
+ url
4126
+ });
4127
+ }
4128
+ }));
4051
4129
  });
4052
4130
  command.command("status").description("Resolve the stored token to its person, label, and expiry.").action(async () => {
4053
4131
  output.result(await auth.status());
@@ -5841,6 +5919,7 @@ const PROCEDURE_DESCRIPTIONS = {
5841
5919
  "comment.start": "Start a comment thread anchored to a canvas location.",
5842
5920
  "comment.resolve": "Set a thread resolved or reopened with an explicit target state.",
5843
5921
  "comment.reply": "Add a reply to an existing comment thread.",
5922
+ "comment.react": "Set or remove one emoji reaction on a comment message.",
5844
5923
  "comment.edit": "Replace the body of a comment message authored by this person.",
5845
5924
  "comment.move": "Move a comment thread anchor to a new canvas location.",
5846
5925
  "comment.delete": "Delete an entire comment thread, or tombstone one message when its id is set.",
@@ -5924,7 +6003,10 @@ const OPTION_DESCRIPTIONS = {
5924
6003
  "--query": "Text to search for in the resources returned by this command.",
5925
6004
  "--client-thread-id": "Client-minted UUID; reuse it when retrying this thread creation.",
5926
6005
  "--client-message-id": "Client-minted UUID; reuse it when retrying this reply.",
6006
+ "--mentioned-person-ids": "Person UUIDs to mention; get them from the relevant people or participants list.",
5927
6007
  "--resolved": "Target state: true resolves the thread; false reopens it.",
6008
+ "--emoji": "Single emoji to add to or remove from the comment message.",
6009
+ "--reacted": "Target state: true adds this person’s reaction; false removes it.",
5928
6010
  "--review-state": "Review state to store: not-started, in-progress, or done.",
5929
6011
  "--confirmation": "Exact current canvas title; get it from the deleted canvas list.",
5930
6012
  "--document": "Complete opaque canvas document as one JSON object.",
@@ -5950,7 +6032,7 @@ const OPTION_DESCRIPTIONS = {
5950
6032
  "--arrived": "Uploaded asset objects as JSON: url, etag, and byteSize.",
5951
6033
  "--provenance": "Origin JSON `{\"sourceRecordingId\":\"UUID\",\"atMs\":0}`, or null for a standalone screen.",
5952
6034
  "--json": "Complete procedure input as JSON; do not combine it with field flags.",
5953
- "auth login --token": "Agent token from a canvas Connect Agent prompt; omit this option to read one line from stdin.",
6035
+ "auth login --token": "Existing agent token for CI or headless fallback; omit it to authenticate in a browser.",
5954
6036
  "canvas.create --organisation-id": "Team UUID from `enhance organisation list`; omit it to create on the personal shelf.",
5955
6037
  "canvas.move --organisation-id": "Destination team UUID from `enhance organisation list`, or the literal `personal`.",
5956
6038
  "canvas.duplicate --organisation-id": "Destination team UUID from `enhance organisation list`, or the literal `personal`.",
@@ -6263,7 +6345,7 @@ const REFUSALS = /* @__PURE__ */ new Set([
6263
6345
  const remediationFor = (code) => {
6264
6346
  switch (code) {
6265
6347
  case "BAD_REQUEST": return "Run the command with '--help', then rewrite every rejected argument.";
6266
- case "UNAUTHORIZED": return "A human must run 'enhance auth login' with a current token.";
6348
+ case "UNAUTHORIZED": return "Run 'enhance auth login' and complete authentication in the browser.";
6267
6349
  case "FORBIDDEN": return "Run 'enhance canvas list --scope mine' and choose a target you can change.";
6268
6350
  case "NOT_FOUND": return "List the resource again and retry with an identifier from that result.";
6269
6351
  case "CONFLICT": return "Read the resource again before retrying the change.";
@@ -6402,6 +6484,129 @@ const registerFixtureProgram = (program, composites, output) => {
6402
6484
  registerWorldFixture(fixture, composites.world, output);
6403
6485
  };
6404
6486
  //#endregion
6487
+ //#region src/infrastructure/oauth-loopback.adapter.ts
6488
+ const CALLBACK_PATH = "/callback";
6489
+ const AUTHORIZATION_TIMEOUT_MS = 12e4;
6490
+ const ENTROPY_BYTES = 32;
6491
+ const HTTP_OK = 200;
6492
+ const HTTP_BAD_REQUEST = 400;
6493
+ const HTTP_NOT_FOUND = 404;
6494
+ const SUCCESS_PAGE = "<!doctype html><meta charset=\"utf-8\"><title>Enhance authenticated</title><p>Enhance is authenticated. You can close this window.</p>";
6495
+ const endpoint = (issuer, path) => new URL(path, issuer.endsWith("/") ? issuer : `${issuer}/`);
6496
+ const launchBrowser = (url) => {
6497
+ const command = process.platform === "darwin" ? {
6498
+ executable: "open",
6499
+ arguments: [url]
6500
+ } : process.platform === "win32" ? {
6501
+ executable: "rundll32.exe",
6502
+ arguments: ["url.dll,FileProtocolHandler", url]
6503
+ } : {
6504
+ executable: "xdg-open",
6505
+ arguments: [url]
6506
+ };
6507
+ const child = spawn(command.executable, command.arguments, {
6508
+ detached: true,
6509
+ stdio: "ignore"
6510
+ });
6511
+ child.once("error", () => false);
6512
+ child.unref();
6513
+ };
6514
+ const handleCallback = (input, request, response) => {
6515
+ const url = new URL(request.url ?? "/", "http://127.0.0.1");
6516
+ if (request.method !== "GET" || url.pathname !== CALLBACK_PATH) {
6517
+ response.writeHead(HTTP_NOT_FOUND).end();
6518
+ return;
6519
+ }
6520
+ if (url.searchParams.get("state") !== input.state) {
6521
+ response.writeHead(HTTP_BAD_REQUEST).end("The OAuth state did not match. Return to the terminal and retry.");
6522
+ return;
6523
+ }
6524
+ const error = url.searchParams.get("error");
6525
+ const received = url.searchParams.get("code");
6526
+ if (error !== null || received === null || received === "") {
6527
+ response.writeHead(HTTP_BAD_REQUEST).end("Enhance authentication was not approved.");
6528
+ input.completion.reject(new Error(error ?? "the authorization response carried no code"));
6529
+ return;
6530
+ }
6531
+ response.writeHead(HTTP_OK, { "content-type": "text/html; charset=utf-8" }).end(SUCCESS_PAGE);
6532
+ input.completion.resolve(received);
6533
+ };
6534
+ const authorizeUrl = (input) => {
6535
+ const authorize = endpoint(input.issuer, "oauth/authorize");
6536
+ authorize.search = new URLSearchParams({
6537
+ response_type: "code",
6538
+ client_id: input.clientId,
6539
+ redirect_uri: input.redirectUri,
6540
+ scope: input.scope,
6541
+ state: input.state,
6542
+ code_challenge: input.challenge,
6543
+ code_challenge_method: "S256"
6544
+ }).toString();
6545
+ return authorize.href;
6546
+ };
6547
+ const authorizationCode = async (input) => {
6548
+ const completion = Promise.withResolvers();
6549
+ const server = createServer((request, response) => {
6550
+ handleCallback({
6551
+ state: input.state,
6552
+ completion
6553
+ }, request, response);
6554
+ });
6555
+ await new Promise((resolve, reject) => {
6556
+ server.once("error", reject);
6557
+ server.listen(0, "127.0.0.1", resolve);
6558
+ });
6559
+ const address = server.address();
6560
+ if (address === null || typeof address === "string") {
6561
+ server.close();
6562
+ throw new Error("the OAuth callback listener has no TCP port");
6563
+ }
6564
+ const redirectUri = `http://127.0.0.1:${String(address.port)}${CALLBACK_PATH}`;
6565
+ const url = authorizeUrl({
6566
+ ...input,
6567
+ redirectUri
6568
+ });
6569
+ input.onReady(url);
6570
+ if (input.openBrowser) launchBrowser(url);
6571
+ const timeout = setTimeout(() => {
6572
+ completion.reject(/* @__PURE__ */ new Error("browser authorization timed out"));
6573
+ }, AUTHORIZATION_TIMEOUT_MS);
6574
+ try {
6575
+ return {
6576
+ code: await completion.promise,
6577
+ redirectUri
6578
+ };
6579
+ } finally {
6580
+ clearTimeout(timeout);
6581
+ await new Promise((resolve) => {
6582
+ server.close(() => {
6583
+ resolve();
6584
+ });
6585
+ });
6586
+ }
6587
+ };
6588
+ const createOauthLoopbackAdapter = (remote) => ({ authorize: async (input) => {
6589
+ try {
6590
+ const verifier = randomBytes(ENTROPY_BYTES).toString("base64url");
6591
+ const challenge = createHash("sha256").update(verifier).digest("base64url");
6592
+ const state = randomBytes(ENTROPY_BYTES).toString("base64url");
6593
+ const authorized = await authorizationCode({
6594
+ ...input,
6595
+ challenge,
6596
+ state
6597
+ });
6598
+ return await remote.exchangeOauthCode({
6599
+ issuer: input.issuer,
6600
+ clientId: input.clientId,
6601
+ code: authorized.code,
6602
+ redirectUri: authorized.redirectUri,
6603
+ verifier
6604
+ });
6605
+ } catch (error) {
6606
+ throw new CliError("UNAUTHORIZED", error instanceof Error ? `Browser authentication failed: ${error.message}.` : "Browser authentication failed.", "Run 'enhance auth login' again, complete the browser consent, and keep the terminal open.");
6607
+ }
6608
+ } });
6609
+ //#endregion
6405
6610
  //#region src/infrastructure/prototype.program.ts
6406
6611
  const finiteNumber = (value) => z.coerce.number().parse(value);
6407
6612
  const positiveNumber = (value) => z.coerce.number().positive().parse(value);
@@ -7104,6 +7309,14 @@ const canvasCommenterProcedure = canvasReaderProcedure.use(async ({ ctx, next })
7104
7309
  viewer: ctx.viewer
7105
7310
  } });
7106
7311
  });
7312
+ /** A direct recipient may invite onward without receiving any owner-level management power. */
7313
+ const canvasSharerProcedure = canvasReaderProcedure.use(async ({ ctx, next }) => {
7314
+ if (!ctx.canvasAccess.canShare || ctx.viewer.kind === "anonymous" || ctx.viewer.kind === "render") throw toTrpcError(appError$1("FORBIDDEN", "only a canvas recipient can share this"));
7315
+ return next({ ctx: {
7316
+ ...ctx,
7317
+ viewer: ctx.viewer
7318
+ } });
7319
+ });
7107
7320
  /**
7108
7321
  * Managing narrows the viewer for the same reason commenting does: `canManage` is only ever
7109
7322
  * true for a member, and a member is somebody.
@@ -7187,6 +7400,7 @@ const toCanvasContract = (view) => ({
7187
7400
  viewerCan: {
7188
7401
  read: view.reach.canRead,
7189
7402
  comment: view.reach.canComment ? "yes" : view.reach.commentNeedsSignIn ? "sign-in" : "no",
7403
+ share: view.reach.canShare,
7190
7404
  manage: view.reach.canManage
7191
7405
  },
7192
7406
  createdAt: view.canvas.createdAt.toISOString(),
@@ -7287,7 +7501,8 @@ const create$2 = (handlers) => personProcedure.input(createCanvasInputSchema).ou
7287
7501
  title: input.title,
7288
7502
  creatorPersonId: ctx.viewer.personId,
7289
7503
  organisationId: input.organisationId,
7290
- sourceUrl: input.sourceUrl
7504
+ sourceUrl: input.sourceUrl,
7505
+ origin: ctx.viewer.kind === "agent" ? "agent" : "dashboard"
7291
7506
  }))));
7292
7507
  const get$1 = (handlers) => canvasReaderProcedure.input(getCanvasInputSchema).output(canvasSchema).query(async ({ input, ctx }) => {
7293
7508
  const view = orThrow(await handlers.get.execute({
@@ -8119,7 +8334,7 @@ const toInviteContract = (invite, at) => ({
8119
8334
  });
8120
8335
  //#endregion
8121
8336
  //#region ../api/src/canvas/infrastructure/canvas-invite.router.ts
8122
- const create$1 = (handlers, shouldExposeTokens) => canvasOwnerProcedure.input(createInviteInputSchema).output(createInviteOutputSchema).mutation(async ({ input, ctx }) => {
8337
+ const create$1 = (handlers, shouldExposeTokens) => canvasSharerProcedure.input(createInviteInputSchema).output(createInviteOutputSchema).mutation(async ({ input, ctx }) => {
8123
8338
  const result = orThrow(await handlers.createInvite.execute({
8124
8339
  ...input,
8125
8340
  invitedByPersonId: ctx.viewer.personId
@@ -8150,7 +8365,7 @@ const accept$1 = (handlers) => personProcedure.input(acceptInviteInputSchema).ou
8150
8365
  });
8151
8366
  return result;
8152
8367
  });
8153
- /** Invitation is the distribution path a link is the alternative to. Owner-only, except accept. */
8368
+ /** Invitation is the distribution path a link is the alternative to. Recipients may invite onward. */
8154
8369
  const createCanvasInviteRouter = (handlers, shouldExposeTokens = false) => trpcRouter({
8155
8370
  create: create$1(handlers, shouldExposeTokens),
8156
8371
  accept: accept$1(handlers),
@@ -8736,6 +8951,21 @@ const toAuthorContract = (message, directory) => ({
8736
8951
  avatarUrl: directory(message.authorPersonId).avatarUrl,
8737
8952
  tokenLabel: message.authorTokenLabel
8738
8953
  });
8954
+ const reactionsOf = (message, directory) => {
8955
+ const grouped = /* @__PURE__ */ new Map();
8956
+ for (const reaction of message.reactions) {
8957
+ const people = grouped.get(reaction.emoji) ?? [];
8958
+ people.push(reaction.personId);
8959
+ grouped.set(reaction.emoji, people);
8960
+ }
8961
+ return [...grouped].map(([emoji, personIds]) => ({
8962
+ emoji,
8963
+ people: personIds.map((personId) => ({
8964
+ personId,
8965
+ name: directory(personId).displayName
8966
+ }))
8967
+ }));
8968
+ };
8739
8969
  const toCommentThreadContract = (view, directory) => {
8740
8970
  const [first] = view.messages;
8741
8971
  return {
@@ -8749,7 +8979,12 @@ const toCommentThreadContract = (view, directory) => {
8749
8979
  body: message.deletedAt === null ? message.body : "(deleted)",
8750
8980
  author: toAuthorContract(message, directory),
8751
8981
  createdAt: message.createdAt.toISOString(),
8752
- editedAt: message.editedAt?.toISOString() ?? null
8982
+ editedAt: message.editedAt?.toISOString() ?? null,
8983
+ mentions: message.mentionedPersonIds.map((personId) => ({
8984
+ personId,
8985
+ name: directory(personId).displayName
8986
+ })),
8987
+ reactions: reactionsOf(message, directory)
8753
8988
  })),
8754
8989
  messageCount: view.thread.messageCount,
8755
8990
  hasMoreMessages: view.thread.messageCount > view.messages.length,
@@ -8812,7 +9047,11 @@ const directoryFor = async (people, views) => {
8812
9047
  const ids = /* @__PURE__ */ new Set();
8813
9048
  for (const view of views) {
8814
9049
  if (view.thread.resolvedByPersonId !== null) ids.add(view.thread.resolvedByPersonId);
8815
- for (const message of view.messages) ids.add(message.authorPersonId);
9050
+ for (const message of view.messages) {
9051
+ ids.add(message.authorPersonId);
9052
+ for (const personId of message.mentionedPersonIds) ids.add(personId);
9053
+ for (const reaction of message.reactions) ids.add(reaction.personId);
9054
+ }
8816
9055
  }
8817
9056
  const entries = orThrow(await people.read([...ids]));
8818
9057
  const byId = new Map(entries.map((entry) => [entry.personId, {
@@ -8845,6 +9084,7 @@ const start$1 = (handlers) => canvasCommenterProcedure.input(startCommentInputSc
8845
9084
  clientThreadId: input.clientThreadId,
8846
9085
  anchor: input.anchor,
8847
9086
  body: input.body,
9087
+ mentionedPersonIds: input.mentionedPersonIds,
8848
9088
  author: authorFrom(ctx.viewer),
8849
9089
  mintMembership: ctx.canvasAccess.accessLevel === null
8850
9090
  }));
@@ -8876,10 +9116,15 @@ const createCommentRouter = (handlers) => trpcRouter({
8876
9116
  list: list$2(handlers),
8877
9117
  start: start$1(handlers),
8878
9118
  resolve: resolve(handlers),
9119
+ react: canvasCommenterProcedure.input(reactToCommentInputSchema).output(commentThreadSchema).mutation(async ({ input, ctx }) => named(handlers.people, orThrow(await handlers.react.execute({
9120
+ ...input,
9121
+ personId: ctx.viewer.personId
9122
+ })))),
8879
9123
  reply: canvasCommenterProcedure.input(replyCommentInputSchema).output(commentThreadSchema).mutation(async ({ input, ctx }) => {
8880
9124
  const view = orThrow(await handlers.reply.execute({
8881
9125
  ...input,
8882
- author: authorFrom(ctx.viewer)
9126
+ author: authorFrom(ctx.viewer),
9127
+ isGuest: ctx.canvasAccess.accessLevel === null
8883
9128
  }));
8884
9129
  ctx.telemetry.emit("CommentReplied", {
8885
9130
  canvasId: input.canvasId,
@@ -9799,6 +10044,7 @@ const handlers = {
9799
10044
  reply: unavailable,
9800
10045
  edit: unavailable,
9801
10046
  move: unavailable,
10047
+ react: unavailable,
9802
10048
  resolve: unavailable,
9803
10049
  remove: unavailable,
9804
10050
  list: unavailable,
@@ -9944,7 +10190,7 @@ const catalogFor = (source) => {
9944
10190
  };
9945
10191
  const registerUtilityPrograms = (program, input) => {
9946
10192
  const screen = createScreenFixtureComposite(input.remote);
9947
- registerAuthProgram(program, createAuthUseCase(input.credentials, input.remote), input.output);
10193
+ registerAuthProgram(program, createAuthUseCase(input.credentials, input.remote, createOauthLoopbackAdapter(input.remote)), input.output);
9948
10194
  registerCommentProgram(program, input.remote, input.output);
9949
10195
  registerDoctorProgram(program, {
9950
10196
  version: input.version,
@@ -9983,7 +10229,7 @@ const createCliProgram = (input) => {
9983
10229
  router: createRemoteRouterAdapter(source, input.remote),
9984
10230
  name: "enhance",
9985
10231
  version: input.version,
9986
- description: "Operate Enhance as the authenticated person, without a browser.",
10232
+ description: "Operate Enhance as the authenticated person.",
9987
10233
  jsonInput: CLI_ASSEMBLY.jsonInput
9988
10234
  });
9989
10235
  const runParams = createRunParams(input);
@@ -9997,7 +10243,7 @@ const createCliProgram = (input) => {
9997
10243
  mutationKey: input.mutationKey,
9998
10244
  output: input.output
9999
10245
  });
10000
- built.description("Operate Enhance as the authenticated person, without a browser.");
10246
+ built.description("Operate Enhance as the authenticated person.");
10001
10247
  const failureState = input.state;
10002
10248
  return {
10003
10249
  program: built,
@@ -10022,7 +10268,7 @@ const createCliProgram = (input) => {
10022
10268
  const configuredDirectory = process.env["ENHANCE3_CONFIG_DIR"];
10023
10269
  const configuredApi = process.env["ENHANCE3_API_URL"];
10024
10270
  const CLI_CONFIG = {
10025
- apiUrl: configuredApi === void 0 || configuredApi === "" ? "http://localhost:3000" : configuredApi,
10271
+ apiUrl: configuredApi === void 0 || configuredApi === "" ? "https://api.enhancelabs.ai" : configuredApi,
10026
10272
  configDirectory: configuredDirectory === void 0 || configuredDirectory === "" ? path.join(homedir(), ".config", "enhance") : configuredDirectory
10027
10273
  };
10028
10274
  //#endregion
@@ -10076,6 +10322,7 @@ const createFileCredentialAdapter = (directory) => {
10076
10322
  const HEALTH_TIMEOUT_MS = 4e3;
10077
10323
  const NOT_FOUND_STATUS = 404;
10078
10324
  const FORBIDDEN_STATUS = 403;
10325
+ const oauthTokenResponseSchema = z.object({ access_token: z.string().min(1) });
10079
10326
  const clientFor = (apiUrl, token, idempotencyKey = null) => createTRPCUntypedClient({ links: [httpLink({
10080
10327
  url: `${apiUrl}/trpc`,
10081
10328
  headers: {
@@ -10088,12 +10335,38 @@ const download = async (url) => {
10088
10335
  if (!response.ok) throw new CliError(response.status === NOT_FOUND_STATUS || response.status === FORBIDDEN_STATUS ? "NOT_FOUND" : "INTERNAL", `Render download answered HTTP ${String(response.status)}.`, "The result may have expired. Request a new render.");
10089
10336
  return new Uint8Array(await response.arrayBuffer());
10090
10337
  };
10338
+ const authenticationConfig = async (apiUrl) => {
10339
+ const response = await fetch(`${apiUrl}/v1/cli-auth`);
10340
+ if (!response.ok) {
10341
+ if (response.status === NOT_FOUND_STATUS) throw new CliError("BAD_REQUEST", "This Enhance API does not support browser authentication.", "Deploy a compatible API, or pass an agent token to 'enhance auth login --token'.");
10342
+ throw new CliError("INTERNAL", `CLI authentication discovery answered HTTP ${String(response.status)}.`, "Run 'enhance doctor', report the result, and stop.");
10343
+ }
10344
+ return response.json();
10345
+ };
10346
+ const exchangeOauthCode = async (input) => {
10347
+ const response = await fetch(new URL("oauth/token", input.issuer.endsWith("/") ? input.issuer : `${input.issuer}/`), {
10348
+ method: "POST",
10349
+ headers: { "content-type": "application/x-www-form-urlencoded" },
10350
+ body: new URLSearchParams({
10351
+ grant_type: "authorization_code",
10352
+ client_id: input.clientId,
10353
+ code: input.code,
10354
+ redirect_uri: input.redirectUri,
10355
+ code_verifier: input.verifier
10356
+ })
10357
+ });
10358
+ if (!response.ok) throw new Error(`token exchange answered HTTP ${String(response.status)}`);
10359
+ return oauthTokenResponseSchema.parse(await response.json()).access_token;
10360
+ };
10091
10361
  const createHttpRemoteAdapter = (apiUrl, credentials, mutationKey) => {
10092
10362
  const normalized = apiUrl.replace(/\/$/, "");
10093
10363
  return {
10364
+ authenticationConfig: async () => authenticationConfig(normalized),
10365
+ exchangeOauthCode,
10094
10366
  query: async (path, input) => clientFor(normalized, await credentials.read()).query(path, input),
10095
10367
  queryWithToken: async (path, input, token) => clientFor(normalized, token).query(path, input),
10096
10368
  mutate: async (procedure, input) => clientFor(normalized, await credentials.read(), mutationKey.current(procedure, input)).mutation(procedure, input),
10369
+ mutateWithToken: async (procedure, input, token) => clientFor(normalized, token).mutation(procedure, input),
10097
10370
  download,
10098
10371
  upload: async (input) => {
10099
10372
  const isStreaming = !(input.body instanceof Uint8Array);
@@ -10347,7 +10620,7 @@ const main = async () => {
10347
10620
  const credentials = createFileCredentialAdapter(CLI_CONFIG.configDirectory);
10348
10621
  const mutationKey = createMutationKeyAdapter();
10349
10622
  const cli = createCliProgram({
10350
- version: "0.1.3",
10623
+ version: "0.1.5",
10351
10624
  credentials,
10352
10625
  remote: createHttpRemoteAdapter(CLI_CONFIG.apiUrl, credentials, mutationKey),
10353
10626
  mutationKey,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@enhance-eng/enhance",
3
- "version": "0.1.3",
3
+ "version": "0.1.5",
4
4
  "private": false,
5
5
  "description": "Agent-first command-line interface for Enhance.",
6
6
  "keywords": [
@@ -31,6 +31,7 @@
31
31
  "prepack": "pnpm run build",
32
32
  "test": "pnpm run test:e2e",
33
33
  "test:e2e": "pnpm run build && node e2e/e2e-runner.ts",
34
+ "test:e2e:browser": "pnpm run build && playwright test",
34
35
  "typecheck": "tsc --noEmit"
35
36
  },
36
37
  "dependencies": {
@@ -46,6 +47,7 @@
46
47
  "@enhance3/api": "workspace:*",
47
48
  "@enhance3/contract": "workspace:*",
48
49
  "@enhance3/tsconfig": "workspace:*",
50
+ "@playwright/test": "^1.62.0",
49
51
  "@types/yauzl": "3.4.0",
50
52
  "@types/yazl": "3.3.1",
51
53
  "@vitest/coverage-v8": "catalog:",