@agent-native/core 0.229.0-nightly-20261116153227 → 0.229.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.
Files changed (50) hide show
  1. package/dist/cli/create.js +9 -6
  2. package/dist/cli/package-lifecycle.js +18 -2
  3. package/dist/cli/process.d.ts +7 -0
  4. package/dist/cli/process.js +20 -0
  5. package/dist/cli/workspace-dev.js +3 -15
  6. package/dist/client/resources/use-resources.d.ts +7 -0
  7. package/dist/client/resources/use-resources.js +24 -2
  8. package/dist/client/review/use-review.d.ts +2 -0
  9. package/dist/client/review/use-review.js +11 -0
  10. package/dist/collab/routes.d.ts +1 -1
  11. package/dist/deploy/build.d.ts +16 -4
  12. package/dist/deploy/build.js +22 -0
  13. package/dist/framework-package-versions.json +11 -11
  14. package/dist/free-name/index.d.ts +11 -3
  15. package/dist/free-name/index.js +8 -6
  16. package/dist/free-name/server.d.ts +1 -1
  17. package/dist/local-artifacts/index.d.ts +13 -0
  18. package/dist/local-artifacts/index.js +75 -2
  19. package/dist/resources/handlers.d.ts +6 -0
  20. package/dist/resources/handlers.js +143 -5
  21. package/dist/resources/store.d.ts +15 -2
  22. package/dist/resources/store.js +60 -8
  23. package/dist/review/actions/create-review-comment.js +7 -3
  24. package/dist/review/actions/reply-review-comment.js +7 -3
  25. package/dist/review/actions/update-review-comment.d.ts +6 -0
  26. package/dist/review/actions/update-review-comment.js +42 -7
  27. package/dist/review/attachments.d.ts +19 -0
  28. package/dist/review/attachments.js +73 -1
  29. package/dist/review/errors.d.ts +4 -0
  30. package/dist/review/errors.js +9 -0
  31. package/dist/review/index.d.ts +1 -1
  32. package/dist/review/index.js +1 -1
  33. package/dist/review/notifications.js +4 -5
  34. package/dist/review/store.d.ts +11 -0
  35. package/dist/review/store.js +21 -2
  36. package/dist/server/first-touch-route.d.ts +1 -1
  37. package/dist/templates/chat/.agents/skills/actions/SKILL.md +2 -1
  38. package/dist/templates/default/.agents/skills/actions/SKILL.md +2 -1
  39. package/dist/templates/headless/.agents/skills/actions/SKILL.md +2 -1
  40. package/dist/templates/workspace-core/.agents/skills/actions/SKILL.md +2 -1
  41. package/dist/testing/cpu-time.d.ts +20 -0
  42. package/dist/testing/cpu-time.js +38 -0
  43. package/dist/usage/actions/get-builder-credit-status.js +7 -3
  44. package/docs/content/toolkit-comments-review.mdx +53 -0
  45. package/migration-manifest.json +1 -1
  46. package/package.json +8 -4
  47. package/src/templates/chat/.agents/skills/actions/SKILL.md +2 -1
  48. package/src/templates/default/.agents/skills/actions/SKILL.md +2 -1
  49. package/src/templates/headless/.agents/skills/actions/SKILL.md +2 -1
  50. package/src/templates/workspace-core/.agents/skills/actions/SKILL.md +2 -1
@@ -2,7 +2,9 @@ import { getQuery, getRouterParam, setResponseHeader, setResponseStatus, readMul
2
2
  import { createError } from "h3";
3
3
  import { fail, isActionContractError } from "../action.js";
4
4
  import { canUpdateAutomationResource } from "../automations/service.js";
5
+ import { isUniqueViolation } from "../db/client.js";
5
6
  import { uploadFile } from "../file-upload/index.js";
7
+ import { nameTaken, nextFreeName } from "../free-name/server.js";
6
8
  import { parseJobResource } from "../jobs/frontmatter.js";
7
9
  import { getOrgContext } from "../org/context.js";
8
10
  import { getSession } from "../server/auth.js";
@@ -12,7 +14,7 @@ import { exportResourcePackSchema, default as exportResourcePack, } from "./acti
12
14
  import { importResourcePackSchema, default as importResourcePack, } from "./actions/import-resource-pack.js";
13
15
  import { getFrontmatterValue, getResourceKind, isRemoteAgentPath, parseFrontmatter, parseCustomAgentProfile, parseRemoteAgentManifest, parseSkillMetadata, } from "./metadata.js";
14
16
  import { RESOURCE_PACK_MAX_BODY_BYTES } from "./pack.js";
15
- import { resourceGet, resourceGetByPath, resourcePut, resourcePutIfAbsent, resourcePutIfCurrent, resourceDelete, resourceDeleteIfCurrent, resourceList, resourceListAccessible, resourceListOrganization, resourceMove, resourceEffectiveContext, ensurePersonalDefaults, canWriteLocalWorkspaceResourcePath, isLocalWorkspaceResourceId, isLegacyOrganizationWorkspaceFile, isLegacySharedResourceVisibleToOrganization, isWorkspaceResourceOwner, organizationIdFromResourceOwner, organizationIdFromWorkspaceResourceOwner, sharedResourceOwner, SHARED_OWNER, WORKSPACE_OWNER, } from "./store.js";
17
+ import { resourceGet, resourceGetByPath, resourcePut, resourcePutIfAbsent, resourcePutIfCurrent, resourcePutIfSnapshot, resourceDelete, resourceDeleteIfCurrent, resourceList, resourceListAccessible, resourceListOrganization, resourceMove, resourceStoredPathsTaken, resourceEffectiveContext, ensurePersonalDefaults, canWriteLocalWorkspaceResourcePath, isLocalWorkspaceResourceId, isSameLocalWorkspaceFile, isLegacyOrganizationWorkspaceFile, isLegacySharedResourceVisibleToOrganization, isWorkspaceResourceOwner, organizationIdFromResourceOwner, organizationIdFromWorkspaceResourceOwner, sharedResourceOwner, SHARED_OWNER, WORKSPACE_OWNER, } from "./store.js";
16
18
  function isSameSkillUpload(incomingContent, existingContent, path) {
17
19
  const incomingSkill = parseSkillMetadata(incomingContent, path);
18
20
  const existingSkill = parseSkillMetadata(existingContent, path);
@@ -434,6 +436,78 @@ export async function handleCreateResource(event) {
434
436
  setResponseStatus(event, 201);
435
437
  return resource;
436
438
  }
439
+ /** How many numbered paths a rename refusal checks for a free one, and how many it asks the database about at once. */
440
+ const FREE_PATH_LIMIT = 1000;
441
+ const FREE_PATH_BATCH = 50;
442
+ /**
443
+ * A free path next to `path` for a resource stored for `owner`: the file's
444
+ * name numbered the way `nextFreeName` numbers it ("notes/todo-2.md"), or
445
+ * for a skill its folder ("skills/review-2/SKILL.md"). Null when none of the
446
+ * paths it checks is free, or when no numbered path could be written: a
447
+ * local workspace file outside skills/ is one of a few fixed names
448
+ * (AGENTS.md, .mcp.json).
449
+ */
450
+ async function freeResourcePath(owner, path, localFiles) {
451
+ if (localFiles && !path.startsWith("skills/"))
452
+ return null;
453
+ const skillName = /^skills\/([^/]+)\/SKILL\.md$/.exec(path)?.[1];
454
+ const folder = path.slice(0, path.lastIndexOf("/") + 1);
455
+ const base = skillName ?? path.slice(folder.length);
456
+ const pathFor = (name) => skillName === undefined ? `${folder}${name}` : `skills/${name}/SKILL.md`;
457
+ // Local files are read one at a time, so the first free one ends the search
458
+ // before a file further on that can't be read.
459
+ const batchSize = localFiles ? 1 : FREE_PATH_BATCH;
460
+ const named = new Set([base]);
461
+ for (let checked = 0; checked < FREE_PATH_LIMIT; checked += batchSize) {
462
+ const names = [];
463
+ while (names.length < batchSize) {
464
+ const name = nextFreeName(base, named);
465
+ named.add(name);
466
+ names.push(name);
467
+ }
468
+ const taken = await suggestionPathsTaken(owner, names.map(pathFor), localFiles);
469
+ const free = names.find((name) => !taken.has(pathFor(name)));
470
+ if (free)
471
+ return pathFor(free);
472
+ }
473
+ return null;
474
+ }
475
+ /**
476
+ * Which numbered paths a suggestion leaves out. A local file that can't be
477
+ * read at one (a folder, a link, a file too big to read) isn't suggested,
478
+ * rather than failing the refusal the suggestion is for.
479
+ */
480
+ async function suggestionPathsTaken(owner, paths, localFiles) {
481
+ try {
482
+ return await resourceStoredPathsTaken(owner, paths, { localFiles });
483
+ }
484
+ catch (error) {
485
+ if (!localFiles)
486
+ throw error;
487
+ return new Set(paths);
488
+ }
489
+ }
490
+ /**
491
+ * The refusal for a rename onto a path another resource already has: a 409
492
+ * `name_taken` carrying a free path, in the shape actions send, so the
493
+ * browser reads it with `isNameTaken` the same way. Without a free path to
494
+ * offer, it's a plain 409. Nothing has been written.
495
+ */
496
+ async function resourcePathTaken(event, owner, path, localFiles) {
497
+ const suggestion = await freeResourcePath(owner, path, localFiles);
498
+ setResponseStatus(event, 409);
499
+ if (!suggestion) {
500
+ return {
501
+ error: `A resource named "${path}" already exists. Rename or delete that one first.`,
502
+ };
503
+ }
504
+ const refusal = nameTaken("resource", path, suggestion);
505
+ return {
506
+ error: refusal.message,
507
+ errorCode: refusal.errorCode,
508
+ details: refusal.details,
509
+ };
510
+ }
437
511
  export async function handleUpdateResource(event) {
438
512
  const id = getRouterParam(event, "id") || event.context.params?.id;
439
513
  if (!id) {
@@ -482,6 +556,9 @@ export async function handleUpdateResource(event) {
482
556
  : undefined;
483
557
  const resource = await resourcePutIfAbsent(activeSharedOwner, nextPath, body.content ?? existing.content, body.mimeType ?? existing.mimeType, writeOptions);
484
558
  if (!resource) {
559
+ if (nextPath !== existing.path) {
560
+ return resourcePathTaken(event, activeSharedOwner, nextPath, false);
561
+ }
485
562
  setResponseStatus(event, 409);
486
563
  return { error: `A resource already exists at path "${nextPath}"` };
487
564
  }
@@ -499,16 +576,77 @@ export async function handleUpdateResource(event) {
499
576
  error: "Local workspace resources can only be moved to AGENTS.md, agent-native.json, mcp.config.json, .mcp.json, or skills/.",
500
577
  };
501
578
  }
579
+ const localFiles = isLocalWorkspaceResource;
580
+ if (nextPath !== existing.path &&
581
+ localFiles &&
582
+ (await isSameLocalWorkspaceFile({
583
+ path: existing.path,
584
+ otherPath: nextPath,
585
+ }))) {
586
+ // The new path is this file again: in another letter case on a
587
+ // case-insensitive disk, or in another skill root's spelling. Writing it
588
+ // and then deleting the old path would delete the file.
589
+ setResponseStatus(event, 409);
590
+ return {
591
+ error: `"${nextPath}" names this same file, so it can't be renamed to it. To change only its letter case, rename it to another name first.`,
592
+ };
593
+ }
594
+ // A rename never writes over another resource. Moving a row onto a taken
595
+ // path trips the (path, owner) index, and for a local workspace file the
596
+ // write below would replace the file already there.
597
+ if (nextPath !== existing.path &&
598
+ (await resourceStoredPathsTaken(existing.owner, [nextPath], { localFiles })).has(nextPath)) {
599
+ return resourcePathTaken(event, existing.owner, nextPath, localFiles);
600
+ }
502
601
  if (!isLocalWorkspaceResource && body.path && body.path !== existing.path) {
503
- await resourceMove(id, body.path);
602
+ try {
603
+ await resourceMove(id, body.path);
604
+ }
605
+ catch (error) {
606
+ // Another write took the path between the check and the move.
607
+ if (!isUniqueViolation(error))
608
+ throw error;
609
+ return resourcePathTaken(event, existing.owner, body.path, false);
610
+ }
504
611
  }
505
612
  const writeOptions = body.metadata !== undefined ? { metadata: body.metadata } : undefined;
613
+ if (isLocalWorkspaceResource && nextPath !== existing.path) {
614
+ // Write the new file only if nothing is there, so a file another write
615
+ // created after the check above is refused rather than replaced. Then
616
+ // delete the old one.
617
+ const moved = await resourcePutIfSnapshot({
618
+ previous: null,
619
+ owner: existing.owner,
620
+ path: nextPath,
621
+ content: body.content ?? existing.content,
622
+ mimeType: body.mimeType ?? existing.mimeType,
623
+ ...(writeOptions ? { options: writeOptions } : {}),
624
+ });
625
+ if (!moved) {
626
+ return resourcePathTaken(event, existing.owner, nextPath, true);
627
+ }
628
+ // The old file goes only if it's still the version just copied. If
629
+ // another write changed or removed it meanwhile, take the copy back, so
630
+ // the newer version isn't lost to a copy of the older one.
631
+ let oldDeleted;
632
+ try {
633
+ oldDeleted = await resourceDeleteIfCurrent(existing);
634
+ }
635
+ catch (error) {
636
+ // The old file couldn't be deleted, so take the copy back too.
637
+ await resourceDeleteIfCurrent(moved.resource);
638
+ throw error;
639
+ }
640
+ if (!oldDeleted) {
641
+ await resourceDeleteIfCurrent(moved.resource);
642
+ setResponseStatus(event, 409);
643
+ return { error: "Resource changed before it could be renamed" };
644
+ }
645
+ return moved.resource;
646
+ }
506
647
  const resource = writeOptions
507
648
  ? await resourcePut(existing.owner, nextPath, body.content ?? existing.content, body.mimeType ?? existing.mimeType, writeOptions)
508
649
  : await resourcePut(existing.owner, nextPath, body.content ?? existing.content, body.mimeType ?? existing.mimeType);
509
- if (isLocalWorkspaceResource && nextPath !== existing.path) {
510
- await resourceDelete(id);
511
- }
512
650
  return resource;
513
651
  }
514
652
  export async function handleDeleteResource(event) {
@@ -1,5 +1,5 @@
1
1
  import { type DbExec, type DbExecStatement } from "../db/client.js";
2
- import { isLocalWorkspaceResourceId } from "../local-artifacts/index.js";
2
+ import { isLocalWorkspaceResourceId, isSameLocalWorkspaceFile } from "../local-artifacts/index.js";
3
3
  import { type StoreWriteOptions } from "../settings/store.js";
4
4
  export declare const SHARED_OWNER = "__shared__";
5
5
  export declare const WORKSPACE_OWNER = "__workspace__";
@@ -133,7 +133,7 @@ export declare const LOCAL_WORKSPACE_RESOURCE_METADATA_SOURCE = "local-workspace
133
133
  /** The app id Dispatch grants this app's workspace resources under, if any. */
134
134
  export declare function resourceWorkspaceAppId(): string | null;
135
135
  export declare function canWriteLocalWorkspaceResourcePath(resourcePath: string): Promise<boolean>;
136
- export { isLocalWorkspaceResourceId };
136
+ export { isLocalWorkspaceResourceId, isSameLocalWorkspaceFile };
137
137
  export declare const resourcesStore: import("../db/store-registry.js").Store;
138
138
  export declare function ensureTable(): Promise<void>;
139
139
  export declare function ensurePersonalDefaults(owner: string): Promise<void>;
@@ -267,3 +267,16 @@ export declare function resourceListAllOwnersWithFingerprint(pathPrefix: string)
267
267
  fingerprint: string;
268
268
  }>;
269
269
  export declare function resourceMove(id: string, newPath: string): Promise<boolean>;
270
+ /**
271
+ * Which of `paths` already hold something a resource stored for `owner`
272
+ * would land on if it moved there. For a local workspace file
273
+ * (`localFiles`), that's a file on disk, found the way a write finds it, so
274
+ * a case-insensitive disk counts "Notes.md" as "notes.md", and a skill counts
275
+ * in either skill root, whichever one the path spells. Otherwise it's a
276
+ * row stored for exactly that owner and path, whatever its visibility, since
277
+ * the (path, owner) index covers every row. Unlike `resourceGetByPath`, it
278
+ * leaves out organization rows and grants, which a move never lands on.
279
+ */
280
+ export declare function resourceStoredPathsTaken(owner: string, paths: readonly string[], options?: {
281
+ localFiles?: boolean;
282
+ }): Promise<Set<string>>;
@@ -8,7 +8,7 @@ import { sql } from "../db/sql.js";
8
8
  import { defineStore } from "../db/store-registry.js";
9
9
  import { widenIntColumnsToBigInt } from "../db/widen-columns.js";
10
10
  import { noteJobFrontmatterWrite } from "../jobs/frontmatter-loss.js";
11
- import { canUseLocalWorkspaceResourcePath, deleteLocalWorkspaceResource, deleteLocalWorkspaceResourceIfCurrent, isLocalWorkspaceResourceId, isLocalWorkspaceResourcesEnabled, listLocalWorkspaceResources, localWorkspaceResourcePathFromId, readLocalWorkspaceResource, writeLocalWorkspaceResourceIfAbsentAtPath, writeLocalWorkspaceResourceIfCurrent, writeLocalWorkspaceResource, } from "../local-artifacts/index.js";
11
+ import { canUseLocalWorkspaceResourcePath, deleteLocalWorkspaceResource, deleteLocalWorkspaceResourceIfCurrent, isLocalWorkspaceResourceId, isLocalWorkspaceResourcesEnabled, isSameLocalWorkspaceFile, listLocalWorkspaceResources, localWorkspaceResourcePathFromId, normalizeLocalWorkspaceResourcePath, readLocalWorkspaceResource, writeLocalWorkspaceResourceIfAbsentAtPath, writeLocalWorkspaceResourceIfCurrent, writeLocalWorkspaceResource, } from "../local-artifacts/index.js";
12
12
  import { getRequestContext, getRequestOrgId, getRequestUserEmail, } from "../server/request-context.js";
13
13
  import { getSetting, putSetting, } from "../settings/store.js";
14
14
  import { isPersistableAttachmentUrl } from "../shared/attachments.js";
@@ -653,6 +653,18 @@ async function localWorkspaceResourceByPath(resourcePath) {
653
653
  const resource = await readLocalWorkspaceResource({ path: resourcePath });
654
654
  return resource ? localWorkspaceResourceToResource(resource) : null;
655
655
  }
656
+ /**
657
+ * The local workspace file a new file at `resourcePath` would clash with. A
658
+ * skill path names the skill, so its copy in either skill root counts,
659
+ * whichever root the path spells.
660
+ */
661
+ async function localWorkspaceResourceClash(resourcePath) {
662
+ if (!canUseLocalWorkspaceResourcePath(resourcePath))
663
+ return null;
664
+ return readLocalWorkspaceResource({
665
+ path: normalizeLocalWorkspaceResourcePath(resourcePath),
666
+ });
667
+ }
656
668
  async function localWorkspaceResourceMetas(pathPrefix, limit) {
657
669
  return (await listLocalWorkspaceResources({
658
670
  ...(limit === undefined ? {} : { maxResults: limit }),
@@ -673,7 +685,7 @@ async function assertWritableWorkspaceResourcePath(resourcePath) {
673
685
  throw new Error("Workspace resources in local file mode must be AGENTS.md, agent-native.json, mcp.config.json, .mcp.json, or under skills/.");
674
686
  }
675
687
  }
676
- export { isLocalWorkspaceResourceId };
688
+ export { isLocalWorkspaceResourceId, isSameLocalWorkspaceFile };
677
689
  function mergeResourceMetas(primary, inherited) {
678
690
  const seen = new Set(primary.map((resource) => resource.path));
679
691
  const merged = [...primary];
@@ -1951,6 +1963,9 @@ function resourceSnapshotMatch(resource) {
1951
1963
  ],
1952
1964
  };
1953
1965
  }
1966
+ function isFileExistsError(error) {
1967
+ return error instanceof Error && "code" in error && error.code === "EEXIST";
1968
+ }
1954
1969
  function localWorkspaceResourceSnapshot(resource) {
1955
1970
  return isLocalWorkspaceResourceId(resource.id)
1956
1971
  ? localWorkspaceResourceMetadataFromResource(resource)
@@ -1984,13 +1999,21 @@ async function resourcePutIfSnapshotInternal(input, emitChange, clientOverride)
1984
1999
  expectedAbsolutePath: localPrevious.absolutePath,
1985
2000
  })
1986
2001
  : await (async () => {
1987
- if (await localWorkspaceResourceByPath(input.path))
2002
+ if (await localWorkspaceResourceClash(input.path))
1988
2003
  return null;
1989
- return writeLocalWorkspaceResource({
1990
- path: input.path,
1991
- content: input.content,
1992
- ifNotExists: true,
1993
- });
2004
+ try {
2005
+ return await writeLocalWorkspaceResource({
2006
+ path: input.path,
2007
+ content: input.content,
2008
+ ifNotExists: true,
2009
+ });
2010
+ }
2011
+ catch (error) {
2012
+ // Another write created the file after the check above.
2013
+ if (isFileExistsError(error))
2014
+ return null;
2015
+ throw error;
2016
+ }
1994
2017
  })();
1995
2018
  if (!written)
1996
2019
  return null;
@@ -2641,3 +2664,32 @@ export async function resourceMove(id, newPath) {
2641
2664
  }
2642
2665
  return moved;
2643
2666
  }
2667
+ /**
2668
+ * Which of `paths` already hold something a resource stored for `owner`
2669
+ * would land on if it moved there. For a local workspace file
2670
+ * (`localFiles`), that's a file on disk, found the way a write finds it, so
2671
+ * a case-insensitive disk counts "Notes.md" as "notes.md", and a skill counts
2672
+ * in either skill root, whichever one the path spells. Otherwise it's a
2673
+ * row stored for exactly that owner and path, whatever its visibility, since
2674
+ * the (path, owner) index covers every row. Unlike `resourceGetByPath`, it
2675
+ * leaves out organization rows and grants, which a move never lands on.
2676
+ */
2677
+ export async function resourceStoredPathsTaken(owner, paths, options = {}) {
2678
+ const candidates = [...new Set(paths)];
2679
+ const taken = new Set();
2680
+ if (candidates.length === 0)
2681
+ return taken;
2682
+ if (options.localFiles) {
2683
+ for (const resourcePath of candidates) {
2684
+ if (await localWorkspaceResourceClash(resourcePath)) {
2685
+ taken.add(resourcePath);
2686
+ }
2687
+ }
2688
+ return taken;
2689
+ }
2690
+ await ensureTable();
2691
+ const { rows } = await getDbExec().execute(sql `SELECT path FROM resources WHERE owner = ${sql.value(owner)} AND path IN ${sql.in(candidates)}`);
2692
+ for (const row of rows)
2693
+ taken.add(String(row.path));
2694
+ return taken;
2695
+ }
@@ -1,6 +1,6 @@
1
1
  import { z } from "zod";
2
2
  import { defineAction } from "../../action.js";
3
- import { sanitizeReviewCommentMetadata } from "../attachments.js";
3
+ import { assertReviewCommentHasContent, sanitizeReviewCommentMetadata, } from "../attachments.js";
4
4
  import { reviewAuthorNameFromContext } from "../identity.js";
5
5
  import { extractReviewMentions, normalizeReviewMentions } from "../mentions.js";
6
6
  import { notifyReviewComment, notifyReviewCommentWithReceipt, } from "../notifications.js";
@@ -45,7 +45,9 @@ const schema = z.object({
45
45
  .nullable()
46
46
  .optional()
47
47
  .describe("The version the anchor was written at; defaults to the latest"),
48
- body: z.string().min(1),
48
+ body: z
49
+ .string()
50
+ .describe("Inline Markdown; may be empty when the comment has an image"),
49
51
  authorName: z.string().nullable().optional(),
50
52
  resolutionTarget: z.enum(["agent", "human"]).nullable().optional(),
51
53
  mentions: z.array(mentionSchema).optional(),
@@ -67,6 +69,8 @@ export default defineAction({
67
69
  run: async (args, ctx) => {
68
70
  const actionCtx = ctx;
69
71
  const access = await assertReviewCommentAccess(args.resourceType, args.resourceId, actionCtx);
72
+ const metadata = await sanitizeReviewCommentMetadata(args.metadata);
73
+ assertReviewCommentHasContent(args.body, metadata);
70
74
  const mentions = normalizeReviewMentions([
71
75
  ...normalizeReviewMentions(args.mentions),
72
76
  ...extractReviewMentions(args.body),
@@ -94,7 +98,7 @@ export default defineAction({
94
98
  ownerEmail: access.ownerEmail ?? actionCtx?.userEmail ?? null,
95
99
  orgId: access.orgId ?? actionCtx?.orgId ?? null,
96
100
  visibility: normalizeReviewVisibility(access.visibility),
97
- metadata: await sanitizeReviewCommentMetadata(args.metadata),
101
+ metadata,
98
102
  };
99
103
  const result = args.clientOperationId
100
104
  ? await insertReviewCommentIdempotently({
@@ -1,6 +1,6 @@
1
1
  import { z } from "zod";
2
2
  import { defineAction, fail } from "../../action.js";
3
- import { sanitizeReviewCommentMetadata } from "../attachments.js";
3
+ import { assertReviewCommentHasContent, sanitizeReviewCommentMetadata, } from "../attachments.js";
4
4
  import { reviewAuthorNameFromContext } from "../identity.js";
5
5
  import { extractReviewMentions, normalizeReviewMentions } from "../mentions.js";
6
6
  import { notifyReviewComment, notifyReviewCommentWithReceipt, } from "../notifications.js";
@@ -15,7 +15,9 @@ const schema = z.object({
15
15
  resourceType: z.string().min(1),
16
16
  resourceId: z.string().min(1),
17
17
  commentId: z.string().min(1),
18
- body: z.string().min(1),
18
+ body: z
19
+ .string()
20
+ .describe("Inline Markdown; may be empty when the reply has an image"),
19
21
  authorName: z.string().nullable().optional(),
20
22
  resolutionTarget: z.enum(["agent", "human"]).nullable().optional(),
21
23
  mentions: z.array(mentionSchema).optional(),
@@ -76,6 +78,8 @@ export default defineAction({
76
78
  errorCode: "thread_not_open",
77
79
  });
78
80
  }
81
+ const metadata = await sanitizeReviewCommentMetadata(args.metadata);
82
+ assertReviewCommentHasContent(args.body, metadata);
79
83
  const mentions = normalizeReviewMentions([
80
84
  ...normalizeReviewMentions(args.mentions),
81
85
  ...extractReviewMentions(args.body),
@@ -112,7 +116,7 @@ export default defineAction({
112
116
  ownerEmail: access.ownerEmail ?? actionCtx?.userEmail ?? null,
113
117
  orgId: access.orgId ?? actionCtx?.orgId ?? null,
114
118
  visibility: normalizeReviewVisibility(access.visibility),
115
- metadata: await sanitizeReviewCommentMetadata(args.metadata),
119
+ metadata,
116
120
  };
117
121
  const resource = {
118
122
  resourceType: args.resourceType,
@@ -3,6 +3,12 @@ declare const _default: import("../../action.js").ActionDefinition<{
3
3
  resourceId: string;
4
4
  commentId: string;
5
5
  body?: string | undefined;
6
+ attachments?: {
7
+ url: string;
8
+ name?: string | undefined;
9
+ contentType?: string | undefined;
10
+ provider?: string | undefined;
11
+ }[] | undefined;
6
12
  anchor?: unknown;
7
13
  anchorKind?: string | null | undefined;
8
14
  anchorVersion?: number | null | undefined;
@@ -2,6 +2,7 @@ import { z } from "zod";
2
2
  import { defineAction } from "../../action.js";
3
3
  import { ForbiddenError } from "../../sharing/access.js";
4
4
  import { roleSatisfies } from "../../sharing/schema.js";
5
+ import { assertReviewCommentHasContent, MAX_REVIEW_IMAGE_ATTACHMENTS, sanitizeReviewCommentAttachmentEdit, } from "../attachments.js";
5
6
  import { extractReviewMentions, normalizeReviewMentions } from "../mentions.js";
6
7
  import { assertPersonReviewAnchorKind, canCommentOnReviewableResource, resolveReviewableResourceAccess, } from "../registry.js";
7
8
  import { getReviewCommentById, updateReviewComment } from "../store.js";
@@ -10,12 +11,28 @@ const mentionSchema = z.object({
10
11
  email: z.string().email().nullable().optional(),
11
12
  id: z.string().nullable().optional(),
12
13
  });
14
+ const attachmentSchema = z.object({
15
+ url: z.string().min(1),
16
+ name: z.string().optional(),
17
+ contentType: z.string().optional(),
18
+ provider: z.string().optional(),
19
+ });
13
20
  const schema = z
14
21
  .object({
15
22
  resourceType: z.string().min(1),
16
23
  resourceId: z.string().min(1),
17
24
  commentId: z.string().min(1),
18
- body: z.string().min(1).optional(),
25
+ body: z
26
+ .string()
27
+ .optional()
28
+ .describe("Inline Markdown; may be empty when the comment has an image"),
29
+ // As many as a comment keeps, so a longer list is refused before any of
30
+ // its URLs are checked, rather than cut short.
31
+ attachments: z
32
+ .array(attachmentSchema)
33
+ .max(MAX_REVIEW_IMAGE_ATTACHMENTS)
34
+ .optional()
35
+ .describe(`The comment's images, in place of the ones it has; at most ${MAX_REVIEW_IMAGE_ATTACHMENTS}`),
19
36
  anchor: z.unknown().optional(),
20
37
  anchorKind: z.string().min(1).nullable().optional(),
21
38
  anchorVersion: z.number().int().positive().nullable().optional(),
@@ -27,11 +44,11 @@ const schema = z
27
44
  .optional()
28
45
  .describe("The comment's revision when read; a newer one refuses the edit with revision_conflict"),
29
46
  })
30
- .refine((args) => args.body !== undefined || args.anchor !== undefined, {
31
- message: "Provide a body or anchor to update",
32
- });
47
+ .refine((args) => args.body !== undefined ||
48
+ args.attachments !== undefined ||
49
+ args.anchor !== undefined, { message: "Provide a body, attachments or anchor to update" });
33
50
  export default defineAction({
34
- description: "Update an authored review comment body or canvas anchor.",
51
+ description: "Update an authored review comment's body or images, or its canvas anchor.",
35
52
  schema,
36
53
  mcpAnnotations: {
37
54
  readOnlyHint: false,
@@ -56,7 +73,9 @@ export default defineAction({
56
73
  const isAuthor = Boolean(actionCtx?.userEmail) &&
57
74
  normalizeEmail(comment.authorEmail) ===
58
75
  normalizeEmail(actionCtx?.userEmail);
59
- const changesContent = args.body !== undefined || args.mentions !== undefined;
76
+ const changesContent = args.body !== undefined ||
77
+ args.mentions !== undefined ||
78
+ args.attachments !== undefined;
60
79
  if (!access ||
61
80
  !canCommentOnReviewableResource(args.resourceType, access) ||
62
81
  (changesContent
@@ -72,6 +91,16 @@ export default defineAction({
72
91
  ? null
73
92
  : comment.anchorKind);
74
93
  }
94
+ // New images that fail a new comment's checks are dropped here too; the
95
+ // ones the comment already keeps stay as they are.
96
+ const attachments = args.attachments === undefined
97
+ ? undefined
98
+ : await sanitizeReviewCommentAttachmentEdit(args.attachments, comment.metadata);
99
+ // Checked here for a quick answer, and again by the store against the
100
+ // locked row, so a change made meanwhile can't empty the comment.
101
+ if (changesContent) {
102
+ assertReviewCommentHasContent(args.body ?? comment.body, attachments === undefined ? comment.metadata : { attachments });
103
+ }
75
104
  const mentions = args.body === undefined
76
105
  ? undefined
77
106
  : normalizeReviewMentions([
@@ -80,6 +109,7 @@ export default defineAction({
80
109
  ]);
81
110
  const updated = await updateReviewComment(args.commentId, {
82
111
  ...(args.body !== undefined ? { body: args.body } : {}),
112
+ ...(attachments !== undefined ? { attachments } : {}),
83
113
  ...(args.anchor !== undefined ? { anchor: args.anchor } : {}),
84
114
  ...(args.anchor !== undefined && args.anchorKind !== undefined
85
115
  ? { anchorKind: args.anchorKind }
@@ -89,7 +119,12 @@ export default defineAction({
89
119
  : {}),
90
120
  ...(mentions !== undefined ? { mentions } : {}),
91
121
  }, { resourceType: args.resourceType, resourceId: args.resourceId }, {
92
- expectedRevision: args.expectedRevision,
122
+ // An image edit is worked out from the comment as read above, so
123
+ // with no revision given it saves only over that one: an image
124
+ // change made since is refused as a conflict rather than undone.
125
+ expectedRevision: args.expectedRevision ??
126
+ (attachments !== undefined ? comment.revision : undefined),
127
+ requireContent: changesContent,
93
128
  actorEmail: actionCtx?.userEmail ?? null,
94
129
  });
95
130
  if (!updated)
@@ -1 +1,20 @@
1
+ /** As many images as one comment keeps. */
2
+ export declare const MAX_REVIEW_IMAGE_ATTACHMENTS = 5;
1
3
  export declare function sanitizeReviewCommentMetadata(metadata: Record<string, unknown> | null | undefined): Promise<Record<string, unknown> | null>;
4
+ /**
5
+ * The attachments an edit gives a comment, in the edit's order. Ones the
6
+ * comment already keeps stay as stored, without their checks running again,
7
+ * so a change of upload provider since never drops them. New ones are checked
8
+ * as a new comment's are.
9
+ *
10
+ * An edit only takes out what its author could see. A stored attachment that
11
+ * fails the checks now is left out of every comment list, so no one editing
12
+ * can have taken it out: it stays, after the edit's own. A comment still keeps
13
+ * at most five, and an edit that would leave more is refused.
14
+ */
15
+ export declare function sanitizeReviewCommentAttachmentEdit(attachments: readonly unknown[], storedMetadata: Record<string, unknown> | null | undefined): Promise<Record<string, unknown>[]>;
16
+ /**
17
+ * Refuses a comment with nothing in it: no text, and no image left once its
18
+ * attachments were checked. An image is a comment on its own.
19
+ */
20
+ export declare function assertReviewCommentHasContent(body: string, metadata: Record<string, unknown> | null): void;
@@ -1,5 +1,7 @@
1
+ import { fail } from "../action.js";
1
2
  import { getActiveFileUploadProviderForRequest } from "../file-upload/registry.js";
2
- const MAX_REVIEW_IMAGE_ATTACHMENTS = 5;
3
+ /** As many images as one comment keeps. */
4
+ export const MAX_REVIEW_IMAGE_ATTACHMENTS = 5;
3
5
  export async function sanitizeReviewCommentMetadata(metadata) {
4
6
  if (!metadata || !Array.isArray(metadata.attachments)) {
5
7
  return metadata ?? null;
@@ -39,6 +41,76 @@ export async function sanitizeReviewCommentMetadata(metadata) {
39
41
  next.attachments = attachments;
40
42
  return next;
41
43
  }
44
+ /**
45
+ * The attachments an edit gives a comment, in the edit's order. Ones the
46
+ * comment already keeps stay as stored, without their checks running again,
47
+ * so a change of upload provider since never drops them. New ones are checked
48
+ * as a new comment's are.
49
+ *
50
+ * An edit only takes out what its author could see. A stored attachment that
51
+ * fails the checks now is left out of every comment list, so no one editing
52
+ * can have taken it out: it stays, after the edit's own. A comment still keeps
53
+ * at most five, and an edit that would leave more is refused.
54
+ */
55
+ export async function sanitizeReviewCommentAttachmentEdit(attachments, storedMetadata) {
56
+ const stored = attachmentsByUrl(storedMetadata?.attachments);
57
+ const sanitized = await sanitizeReviewCommentMetadata({
58
+ attachments: attachments.filter((value) => {
59
+ const url = attachmentUrl(value);
60
+ return url !== null && !stored.has(url);
61
+ }),
62
+ });
63
+ const checked = attachmentsByUrl(sanitized?.attachments);
64
+ const next = [];
65
+ const taken = new Set();
66
+ for (const value of attachments) {
67
+ const url = attachmentUrl(value);
68
+ const attachment = url ? (stored.get(url) ?? checked.get(url)) : undefined;
69
+ if (!url || !attachment || taken.has(url))
70
+ continue;
71
+ taken.add(url);
72
+ next.push(attachment);
73
+ }
74
+ // The stored ones a comment list shows, as `list-review-comments` reads them.
75
+ const listed = attachmentsByUrl((await sanitizeReviewCommentMetadata({ attachments: [...stored.values()] }))
76
+ ?.attachments);
77
+ for (const [url, attachment] of stored) {
78
+ if (!listed.has(url) && !taken.has(url))
79
+ next.push(attachment);
80
+ }
81
+ if (next.length > MAX_REVIEW_IMAGE_ATTACHMENTS) {
82
+ fail(`A comment keeps at most ${MAX_REVIEW_IMAGE_ATTACHMENTS} images, counting ones it already has that can't be shown.`, { errorCode: "too_many_images" });
83
+ }
84
+ return next;
85
+ }
86
+ function attachmentUrl(value) {
87
+ if (!value || typeof value !== "object")
88
+ return null;
89
+ const url = value.url;
90
+ return typeof url === "string" && url.trim() ? url.trim() : null;
91
+ }
92
+ function attachmentsByUrl(values) {
93
+ const byUrl = new Map();
94
+ if (!Array.isArray(values))
95
+ return byUrl;
96
+ for (const value of values) {
97
+ const url = attachmentUrl(value);
98
+ if (url && !byUrl.has(url)) {
99
+ byUrl.set(url, value);
100
+ }
101
+ }
102
+ return byUrl;
103
+ }
104
+ /**
105
+ * Refuses a comment with nothing in it: no text, and no image left once its
106
+ * attachments were checked. An image is a comment on its own.
107
+ */
108
+ export function assertReviewCommentHasContent(body, metadata) {
109
+ const images = metadata?.attachments;
110
+ if (body.trim() || (Array.isArray(images) && images.length > 0))
111
+ return;
112
+ fail("A comment needs text or an image.", { errorCode: "empty_comment" });
113
+ }
42
114
  function isReviewImageAttachmentContentType(contentType) {
43
115
  return contentType === undefined || contentType.startsWith("image/");
44
116
  }
@@ -19,6 +19,10 @@ export declare class ReviewCommentRevisionConflictError extends ReviewStorageErr
19
19
  readonly currentRevision: number;
20
20
  constructor(commentId: string, currentRevision: number);
21
21
  }
22
+ /** An edit that would leave a comment with no text and no image. */
23
+ export declare class ReviewCommentEmptyError extends ReviewStorageError {
24
+ constructor(commentId: string);
25
+ }
22
26
  /** An outside ID already linked to another comment. */
23
27
  export declare class ReviewCommentLinkConflictError extends ReviewStorageError {
24
28
  constructor(provider: string, externalKind: string, externalId: string);
@@ -32,6 +32,15 @@ export class ReviewCommentRevisionConflictError extends ReviewStorageError {
32
32
  this.currentRevision = currentRevision;
33
33
  }
34
34
  }
35
+ /** An edit that would leave a comment with no text and no image. */
36
+ export class ReviewCommentEmptyError extends ReviewStorageError {
37
+ constructor(commentId) {
38
+ super("A comment needs text or an image.", "empty_comment", 400, {
39
+ commentId,
40
+ });
41
+ this.name = "ReviewCommentEmptyError";
42
+ }
43
+ }
35
44
  /** An outside ID already linked to another comment. */
36
45
  export class ReviewCommentLinkConflictError extends ReviewStorageError {
37
46
  constructor(provider, externalKind, externalId) {