🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(work): let agents create, update and delete their Works (#23469)
YuTengjing9463328d5887
diff --git a/.agents/skills/agent-work/SKILL.md b/.agents/skills/agent-work/SKILL.mdindex d9194f58b4e..8070670416d 100644--- a/.agents/skills/agent-work/SKILL.md+++ b/.agents/skills/agent-work/SKILL.md@@ -15,9 +15,9 @@ Two tables (`packages/database/src/schemas/work.ts`):## Type registry-`packages/database/src/models/work/registry.ts` is the single registry of Work types (`document` / `external` / `file` / `task`): `WORK_TYPE_ADAPTERS` is `satisfies Record<WorkType, WorkTypeAdapter>`, so a type added to `@lobechat/types` without an adapter is a compile error.+`packages/database/src/models/work/registry.ts` is the single registry of Work types (`canvas` / `document` / `external` / `file` / `collection` / `goal_report` / `task`): `WORK_TYPE_ADAPTERS` is `satisfies Record<WorkType, WorkTypeAdapter>`, so a type added to `@lobechat/types` without an adapter is a compile error.-**Read-path compatibility gate**: `OPT_IN_WORK_TYPES` (currently `{'file'}`) hides newer types from clients that did not opt in (`includeFileWorks`). Released Electron clients lag by weeks and crash on unknown type descriptors (`descriptor.getIcon` on `undefined`), so a request without the opt-in receives exactly the pre-`file` set. Any NEW Work type must ship behind the same kind of opt-in.+**Read-path compatibility gate**: `OPT_IN_WORK_TYPES` (currently `{'canvas', 'file', 'collection'}`) hides newer types from clients that did not opt in (`includeFileWorks`). Released Electron clients lag by weeks and crash on unknown type descriptors (`descriptor.getIcon` on `undefined`), so a request without the opt-in receives exactly the pre-`file` set. Any NEW Work type must ship behind the same kind of opt-in.The gate has two kinds of emission points, and both must honor the client's declaration:@@ -42,7 +42,7 @@ A share visitor's run executes as the creator, so owner scope alone cannot separ## Registration write paths-Four write paths, two timing classes:+Five write paths, two timing classes:| Path | When | Where || ----------------------------------------------------------------------- | ----------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- |@@ -50,6 +50,19 @@ Four write paths, two timing classes:| Shell Work scan (hetero codex/claude-code + device `lobe-local-system`) | at operation completion | `apps/server/src/services/workRegistration/shellWorkRegistration.ts` via `registerWorksForOperation` || File Work scan (sandbox entity files) | at operation completion | `apps/server/src/services/workRegistration/registerWorksForOperation.ts` || Task / document works | at creation by their owning feature | `WorkModel.registerTask` / `registerDocument` |+| Agent-created files and links (`lh work create\|update\|delete`) | at the CLI call, during the run | `work.createAgentWork` / `updateAgentWork` / `deleteAgentWork` → the same-named `WorkModel` methods (`packages/database/src/models/work/agentWork.ts`) |+| Agent-created collections and links (`lobe-work` tool) | at the tool call, during the run | `apps/server/src/services/toolExecution/serverRuntimes/work.ts` → the same `WorkModel` methods |++### Agent-created Works and `agentEditable`++`works.metadata.agentEditable` is stamped once, when the identity is first registered, and decides whether the agent may change the Work later. `lh work` and the `lobe-work` tool stamp it on everything they create; every other path leaves it unset unless the tool API's manifest `work` config declares `agentEditable: true` (`PluginApiWorkConfig`). Update and delete refuse a Work without the flag, a Work of another user, and a Work no version of which came from the run's conversation; delete also refuses a Work a goal node, delivery or project references (those links cascade from the Work, so deleting it would silently drop them). They handle only file, link and collection Works: a task or document card mirrors its own resource, so rewriting the card title would leave the two disagreeing. `lh work create` also refuses to add a version to an auto-collected Work with the same identity (for example a file path the completion scan already registered). Declare future agent-facing field policy (such as a system-owned price) on the same manifest config instead of special-casing write paths.++- The run is resolved server-side from `operationId` (`resolveAgentWorkRun`): topic, agent and share scope come from the operation row, and versions are stamped with the root of its `parentOperationId` chain so run completion fills their cost; and an operation token needs the `work:write` capability. A desktop-local run has no operation row and cannot use it.+- The CLI sends only the uploaded file id; size, type and URL come from the file row (`resolveAgentWorkFile`).+- Links register as external `resourceType: 'link'` with `<userId>:<topicId>:<canonical URL>` as identity (`linkWorkResourceId`), like file Works: the same link again in the same conversation adds a version, while another conversation or workspace member gets a Work of its own. `works.url` holds the URL; `lh work update` never changes it (the identity would then name the old URL), so a new URL is a new Work. GitHub and Linear links are refused because their own paths register them.+- A `collection` Work (`resourceType: 'collection'`, `col_` resource id) holds an ordered image list in `work_versions.metadata.collection`; every create is a new collection and every update stores the complete list. `works.url` holds the cover URL for list rows. Images must be files the run's user generated or uploaded as run output (`resolveAgentWorkCollectionItems`), named by the `generationId` image generation lists (resolved through `generations.fileId`), a file id or a `/f/<id>` link. In a share visitor run the named id must appear in a tool result (`role = 'tool'`) of the visitor topic; a visitor's own message or an assistant echo does not count. The item count is checked before any image is resolved.+- Delete removes the Work row and, through the FK cascade, its versions; the files stay.+- `rootOperationId` is the run's operation, so the completion lifecycle stamps the display anchor; the card appears after the run completes.### Execution-time: skill providersdiff --git a/.agents/skills/cli/SKILL.md b/.agents/skills/cli/SKILL.mdindex 502ba2a69fc..8c3c13b7f1e 100644--- a/.agents/skills/cli/SKILL.md+++ b/.agents/skills/cli/SKILL.md@@ -91,53 +91,54 @@ apps/cli/src/## Command Groups-| Command | Alias | Description |-| ------------------ | ----- | ---------------------------------------------------------------------------------- |-| `lh login` | - | Authenticate via OIDC Device Code Flow or API key |-| `lh logout` | - | Clear stored credentials |-| `lh connect` | - | Device gateway connection & daemon management |-| `lh device` | - | Manage connected devices |-| `lh status` | - | Quick gateway connectivity check |-| `lh doctor` | - | Diagnose machine readiness (runtime, endpoints, credentials, scope, device, agent) |-| `lh agent` | - | Agent CRUD, run, status |-| `lh agent-group` | - | Agent group CRUD |-| `lh agent-signal` | - | Inspect and trigger Agent Signal source events |-| `lh hetero` | - | Run heterogeneous agent CLIs (Claude Code, Codex, etc.), stream their output |-| `lh goal` | - | Run long-horizon Goal Graphs |-| `lh project` | - | Manage goal-oriented projects |-| `lh task` | - | Manage agent tasks (assignees, checkpoints, deps, review) |-| `lh thread` | - | Manage message threads |-| `lh trace` | - | Inspect and replay recorded agent execution traces |-| `lh acceptance` | - | Delivery acceptances: review loop, rounds, per-run check plans, criteria, rubrics |-| `lh verify` | - | Deprecated alias of `lh acceptance` commands |-| `lh eval` | - | Manage evaluation workflows and benchmarks |-| `lh generate` | `gen` | Content generation (text, image, video, tts, asr, download) |-| `lh doc` | - | Document CRUD, batch-create, parse, topic linking |-| `lh file` | - | File list, view, delete, recent |-| `lh artifact` | - | Publish local HTML pages as artifacts |-| `lh automation` | - | Automations (alias `automations`): list, view, rename, check, delete |-| `lh kb` | - | Knowledge base CRUD, folders, docs, upload, tree view |-| `lh memory` | - | User memory CRUD + extraction |-| `lh message` | - | Message list, search, delete, count, heatmap |-| `lh topic` | - | Topic CRUD + search + recent |-| `lh notify` | - | Send a callback message to a topic and trigger the agent to process it |-| `lh notification` | - | Notification settings: show, enable/disable channels, IM platforms and types |-| `lh migrate` | - | Import data from external tools (OpenClaw, ChatGPT, Claude, etc.) |-| `lh bot` | - | Manage bot integrations (channels, access policies, messengers) |-| `lh skill` | - | Skill CRUD + import (GitHub/URL/market) |-| `lh model` | - | Model CRUD, toggle, batch-toggle, clear |-| `lh provider` | - | Provider CRUD, config, test, toggle |-| `lh legacy-plugin` | - | Legacy 1.0 plugins: list, search, uninstall, update |-| `lh search` | - | Global search across all types |-| `lh session-group` | - | Manage agent session groups |-| `lh workspace` | `ws` | Workspace list, scope switch, members, invites, usage |-| `lh user` | - | Manage user account and settings |-| `lh webhook` | - | Custom webhooks (alias `webhooks`): create, edit, pause, test, rotate-key, calls |-| `lh whoami` | - | Current user info (including the resolved workspace scope) |-| `lh usage` | - | Monthly/daily usage statistics |-| `lh man` | - | Show a manual page for the CLI or a subcommand |-| `lh completion` | - | Output shell completion script |-| `lh update` | - | Update the CLI to the latest published version |+| Command | Alias | Description |+| ------------------ | ----- | ----------------------------------------------------------------------------------- |+| `lh login` | - | Authenticate via OIDC Device Code Flow or API key |+| `lh logout` | - | Clear stored credentials |+| `lh connect` | - | Device gateway connection & daemon management |+| `lh device` | - | Manage connected devices |+| `lh status` | - | Quick gateway connectivity check |+| `lh doctor` | - | Diagnose machine readiness (runtime, endpoints, credentials, scope, device, agent) |+| `lh agent` | - | Agent CRUD, run, status |+| `lh agent-group` | - | Agent group CRUD |+| `lh agent-signal` | - | Inspect and trigger Agent Signal source events |+| `lh hetero` | - | Run heterogeneous agent CLIs (Claude Code, Codex, etc.), stream their output |+| `lh goal` | - | Run long-horizon Goal Graphs |+| `lh project` | - | Manage goal-oriented projects |+| `lh task` | - | Manage agent tasks (assignees, checkpoints, deps, review) |+| `lh thread` | - | Manage message threads |+| `lh trace` | - | Inspect and replay recorded agent execution traces |+| `lh acceptance` | - | Delivery acceptances: review loop, rounds, per-run check plans, criteria, rubrics |+| `lh verify` | - | Deprecated alias of `lh acceptance` commands |+| `lh eval` | - | Manage evaluation workflows and benchmarks |+| `lh generate` | `gen` | Content generation (text, image, video, tts, asr, download) |+| `lh doc` | - | Document CRUD, batch-create, parse, topic linking |+| `lh file` | - | File list, view, delete, recent |+| `lh artifact` | - | Publish local HTML pages as artifacts |+| `lh automation` | - | Automations (alias `automations`): list, view, rename, check, delete |+| `lh kb` | - | Knowledge base CRUD, folders, docs, upload, tree view |+| `lh memory` | - | User memory CRUD + extraction |+| `lh message` | - | Message list, search, delete, count, heatmap |+| `lh topic` | - | Topic CRUD + search + recent |+| `lh notify` | - | Send a callback message to a topic and trigger the agent to process it |+| `lh notification` | - | Notification settings: show, enable/disable channels, IM platforms and types |+| `lh migrate` | - | Import data from external tools (OpenClaw, ChatGPT, Claude, etc.) |+| `lh bot` | - | Manage bot integrations (channels, access policies, messengers) |+| `lh skill` | - | Skill CRUD + import (GitHub/URL/market) |+| `lh model` | - | Model CRUD, toggle, batch-toggle, clear |+| `lh provider` | - | Provider CRUD, config, test, toggle |+| `lh legacy-plugin` | - | Legacy 1.0 plugins: list, search, uninstall, update |+| `lh search` | - | Global search across all types |+| `lh work` | - | Register the files and links an agent run produced as Works, update, delete, lookup |+| `lh session-group` | - | Manage agent session groups |+| `lh workspace` | `ws` | Workspace list, scope switch, members, invites, usage |+| `lh user` | - | Manage user account and settings |+| `lh webhook` | - | Custom webhooks (alias `webhooks`): create, edit, pause, test, rotate-key, calls |+| `lh whoami` | - | Current user info (including the resolved workspace scope) |+| `lh usage` | - | Monthly/daily usage statistics |+| `lh man` | - | Show a manual page for the CLI or a subcommand |+| `lh completion` | - | Output shell completion script |+| `lh update` | - | Update the CLI to the latest published version |### Workspace Scopediff --git a/apps/cli/src/commands/work.test.ts b/apps/cli/src/commands/work.test.tsindex f5033b480a8..202634563ba 100644--- a/apps/cli/src/commands/work.test.ts+++ b/apps/cli/src/commands/work.test.ts@@ -1,15 +1,30 @@+import path from 'node:path';+import { Command } from 'commander';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { registerWorkCommand } from './work';-const mocks = vi.hoisted(() => ({ lookup: vi.fn(), workspace: vi.fn() }));+const mocks = vi.hoisted(() => ({+ create: vi.fn(),+ delete: vi.fn(),+ lookup: vi.fn(),+ update: vi.fn(),+ upload: vi.fn(),+ workspace: vi.fn(),+}));vi.mock('../api/client', () => ({getTrpcClient: async () => ({- work: { lookupPullRequest: { query: mocks.lookup } },+ work: {+ createAgentWork: { mutate: mocks.create },+ deleteAgentWork: { mutate: mocks.delete },+ lookupPullRequest: { query: mocks.lookup },+ updateAgentWork: { mutate: mocks.update },+ },workspace: { getById: { query: mocks.workspace } },}),}));+vi.mock('../utils/uploadLocalFile', () => ({ uploadLocalFile: mocks.upload }));const url = 'https://github.com/owner/repo/pull/12/files';const topics = [@@ -77,3 +92,126 @@ describe('work lookup', () => {expect(mocks.workspace).not.toHaveBeenCalled();});});++const runWork = async (...args: string[]) => {+ const program = new Command().exitOverride();+ registerWorkCommand(program);+ await program.parseAsync(['work', ...args], { from: 'user' });+};++describe('work create / update', () => {+ const created = { id: 'work_1', title: 'report.pdf', url: 'https://app.example.com/f/file_1' };++ beforeEach(() => {+ for (const mock of [mocks.create, mocks.update, mocks.upload]) mock.mockReset();+ mocks.create.mockResolvedValue(created);+ mocks.update.mockResolvedValue(created);+ mocks.upload.mockResolvedValue({ id: 'file_1' });+ vi.stubEnv('LOBEHUB_OPERATION_ID', 'op_run');+ });++ afterEach(() => {+ vi.restoreAllMocks();+ vi.unstubAllEnvs();+ });++ it('uploads a file as the run output and registers it by absolute path', async () => {+ const out = vi.spyOn(console, 'log').mockImplementation(() => {});+ await runWork('create', '--file', 'out/report.pdf', '--description', 'Q3 numbers');++ const absolutePath = path.resolve('out/report.pdf');+ expect(mocks.upload).toHaveBeenCalledWith(expect.anything(), absolutePath, {+ source: 'tool-result',+ });+ expect(mocks.create).toHaveBeenCalledWith({+ description: 'Q3 numbers',+ fileId: 'file_1',+ filePath: absolutePath,+ operationId: 'op_run',+ title: undefined,+ type: 'file',+ });+ expect(out).toHaveBeenCalledWith('Created Work work_1: report.pdf');+ });++ it('registers a link with its title and prints JSON', async () => {+ const out = vi.spyOn(console, 'log').mockImplementation(() => {});+ await runWork(+ 'create',+ '--url',+ 'https://preview.example.com',+ '--title',+ 'Preview',+ '--operation',+ 'op_flag',+ '--json',+ );++ expect(mocks.upload).not.toHaveBeenCalled();+ expect(mocks.create).toHaveBeenCalledWith({+ description: undefined,+ operationId: 'op_flag',+ title: 'Preview',+ type: 'link',+ url: 'https://preview.example.com',+ });+ expect(JSON.parse(out.mock.calls[0][0])).toEqual(created);+ });++ it.each([+ [['create'], 'Pass exactly one of --file or --url'],+ [['create', '--file', 'a.pdf', '--url', 'https://x.example.com'], 'Pass exactly one'],+ [['create', '--url', 'https://x.example.com'], '--title is required with --url'],+ [['update', 'work_1'], 'Pass at least one of'],+ ])('rejects %j before calling the server', async (args, message) => {+ await expect(runWork(...args)).rejects.toThrow(message);+ expect(mocks.create).not.toHaveBeenCalled();+ expect(mocks.update).not.toHaveBeenCalled();+ });++ it('needs a running operation', async () => {+ vi.stubEnv('LOBEHUB_OPERATION_ID', '');+ await expect(runWork('create', '--file', 'a.pdf')).rejects.toThrow('--operation');+ expect(mocks.upload).not.toHaveBeenCalled();+ });++ it('updates a Work with a newly uploaded file and leaves other fields out', async () => {+ vi.spyOn(console, 'log').mockImplementation(() => {});+ await runWork('update', 'work_1', '--file', 'out/report.pdf');++ expect(mocks.update).toHaveBeenCalledWith({+ description: undefined,+ fileId: 'file_1',+ operationId: 'op_run',+ title: undefined,+ workId: 'work_1',+ });+ });+});++describe('work delete', () => {+ beforeEach(() => {+ mocks.delete.mockReset();+ mocks.delete.mockResolvedValue({ id: 'work_1', title: 'Wrong shelf' });+ vi.stubEnv('LOBEHUB_OPERATION_ID', 'op_run');+ });++ afterEach(() => {+ vi.restoreAllMocks();+ vi.unstubAllEnvs();+ });++ it('deletes the Work under the running operation', async () => {+ const out = vi.spyOn(console, 'log').mockImplementation(() => {});+ await runWork('delete', 'work_1');++ expect(mocks.delete).toHaveBeenCalledWith({ operationId: 'op_run', workId: 'work_1' });+ expect(out).toHaveBeenCalledWith('Deleted Work work_1: Wrong shelf');+ });++ it('needs a running operation', async () => {+ vi.stubEnv('LOBEHUB_OPERATION_ID', '');+ await expect(runWork('delete', 'work_1')).rejects.toThrow('--operation');+ expect(mocks.delete).not.toHaveBeenCalled();+ });+});diff --git a/apps/cli/src/commands/work.ts b/apps/cli/src/commands/work.tsindex 5dd188c5b7a..51a061b4a28 100644--- a/apps/cli/src/commands/work.ts+++ b/apps/cli/src/commands/work.ts@@ -1,7 +1,10 @@+import path from 'node:path';+import type { Command } from 'commander';-import { getTrpcClient } from '../api/client';+import { getTrpcClient, type TrpcClient } from '../api/client';import { outputJson, printTable } from '../utils/format';+import { uploadLocalFile } from '../utils/uploadLocalFile';import { resolveUrlBuilder, resourcePath } from './resourceUrl';interface LinkedTopic {@@ -11,8 +14,152 @@ interface LinkedTopic {topicId: string;}+interface AgentWorkOptions {+ description?: string;+ file?: string;+ json?: boolean;+ operation?: string;+ title?: string;+ url?: string;+}++interface RegisteredWork {+ id: string;+ title: string;+ url?: string | null;+}++const requireOperationId = (options: AgentWorkOptions) => {+ const operationId = options.operation ?? process.env.LOBEHUB_OPERATION_ID;+ if (!operationId) {+ throw new Error(+ 'lh work registers Works of a running agent: pass --operation or run it inside an agent run (LOBEHUB_OPERATION_ID)',+ );+ }+ return operationId;+};++/**+ * Upload a produced file as the run's own output. The `tool-result` source+ * keeps it out of the resource library, and is the source an operation token+ * may write.+ */+const uploadWorkFile = async (client: TrpcClient, filePath: string) => {+ const absolutePath = path.resolve(filePath);+ const file = (await uploadLocalFile(client, absolutePath, { source: 'tool-result' })) as {+ id: string;+ };+ return { absolutePath, fileId: file.id };+};++const printWork = (work: RegisteredWork, options: AgentWorkOptions, verb: string) => {+ if (options.json) outputJson(work);+ else console.log(`${verb} Work ${work.id}: ${work.title}`);+};+export function registerWorkCommand(program: Command) {- const work = program.command('work').description('Look up agent work');+ const work = program+ .command('work')+ .description('Register the files and links this agent produced as Works, or look them up');++ work+ .command('create')+ .description(+ [+ 'Register a file or link this agent produced as a Work card under its reply.',+ 'Pass exactly one of --file or --url. Creating the same file path or link again in',+ 'this conversation adds a new version. GitHub and Linear links are registered',+ 'automatically when you create or edit them; do not pass them here.',+ ].join('\n'),+ )+ .option('--file <path>', 'Local file to upload and register')+ .option('--url <url>', 'http(s) link to register; requires --title')+ .option('--title <title>', 'Card title (defaults to the file name for --file)')+ .option('--description <text>', 'Card description')+ .option('--operation <id>', 'Defaults to LOBEHUB_OPERATION_ID')+ .option('--json', 'Output JSON')+ .action(async (options: AgentWorkOptions) => {+ if (Boolean(options.file) === Boolean(options.url)) {+ throw new Error('Pass exactly one of --file or --url');+ }+ if (options.url && !options.title) throw new Error('--title is required with --url');+ const operationId = requireOperationId(options);+ const client = await getTrpcClient();+ const text = { description: options.description, operationId, title: options.title };++ let created: RegisteredWork;+ if (options.url) {+ created = await client.work.createAgentWork.mutate({+ ...text,+ title: options.title!,+ type: 'link',+ url: options.url,+ });+ } else {+ const { absolutePath, fileId } = await uploadWorkFile(client, options.file!);+ created = await client.work.createAgentWork.mutate({+ ...text,+ fileId,+ filePath: absolutePath,+ type: 'file',+ });+ }+ printWork(created, options, 'Created');+ });++ work+ .command('update')+ .argument('<work-id>', 'Id of a Work this agent created with lh work create')+ .description(+ [+ 'Add a version to a Work this agent created. Options left out keep their values.',+ 'A link Work keeps its URL; register a new link with lh work create --url.',+ 'Works registered automatically (GitHub, Linear, scanned files) cannot be updated.',+ ].join('\n'),+ )+ .option('--file <path>', 'New content for a file Work')+ .option('--title <title>', 'New card title')+ .option('--description <text>', 'New card description')+ .option('--operation <id>', 'Defaults to LOBEHUB_OPERATION_ID')+ .option('--json', 'Output JSON')+ .action(async (workId: string, options: AgentWorkOptions) => {+ if (!options.file && !options.title && options.description === undefined) {+ throw new Error('Pass at least one of --file, --title or --description');+ }+ const operationId = requireOperationId(options);+ const client = await getTrpcClient();+ const fileId = options.file ? (await uploadWorkFile(client, options.file)).fileId : undefined;++ const updated: RegisteredWork = await client.work.updateAgentWork.mutate({+ description: options.description,+ fileId,+ operationId,+ title: options.title,+ workId,+ });+ printWork(updated, options, 'Updated');+ });++ work+ .command('delete')+ .argument('<work-id>', 'Id of a Work this agent created with lh work create')+ .description(+ [+ 'Delete a Work this agent created by mistake: its card and versions are removed,',+ 'uploaded files stay. Works registered automatically cannot be deleted.',+ ].join('\n'),+ )+ .option('--operation <id>', 'Defaults to LOBEHUB_OPERATION_ID')+ .option('--json', 'Output JSON')+ .action(async (workId: string, options: AgentWorkOptions) => {+ const operationId = requireOperationId(options);+ const client = await getTrpcClient();+ const deleted: { id: string; title: string | null } =+ await client.work.deleteAgentWork.mutate({ operationId, workId });++ if (options.json) outputJson(deleted);+ else console.log(`Deleted Work ${deleted.id}${deleted.title ? `: ${deleted.title}` : ''}`);+ });work.command('lookup')diff --git a/apps/cli/src/utils/uploadLocalFile.ts b/apps/cli/src/utils/uploadLocalFile.tsindex 1dd33c44106..dbabaa3208c 100644--- a/apps/cli/src/utils/uploadLocalFile.ts+++ b/apps/cli/src/utils/uploadLocalFile.ts@@ -11,6 +11,8 @@ import { rasterDimensions } from './rasterDimensions';export interface UploadLocalFileOptions {knowledgeBaseId?: string;parentId?: string;+ /** File source stored on the record, e.g. `tool-result` for a run's own output. */+ source?: string;}export interface UploadFileBufferInput {@@ -102,6 +104,7 @@ export const uploadFileBuffer = async (name: fileName,parentId: options.parentId,size: buffer.length,+ source: options.source,url: pathname,});} catch (error) {diff --git a/apps/server/src/routers/lambda/__tests__/aiAgent.heteroShareVisitor.test.ts b/apps/server/src/routers/lambda/__tests__/aiAgent.heteroShareVisitor.test.tsindex d214de9a71a..c4d0c84c80a 100644--- a/apps/server/src/routers/lambda/__tests__/aiAgent.heteroShareVisitor.test.ts+++ b/apps/server/src/routers/lambda/__tests__/aiAgent.heteroShareVisitor.test.ts@@ -4,8 +4,9 @@ import { agentOperations, topics } from '@lobechat/database/schemas';import { getTestDB } from '@lobechat/database/test-utils';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { resolveHeteroRunShareVisitor } from '@/server/services/heterogeneousAgent/shareVisitor';+import { aiAgentRouter } from '../aiAgent';-import { resolveHeteroRunShareVisitor } from '../aiAgent/guards';import { cleanupTestUser, createTestUser } from './integration/setup';let testDB: LobeChatDatabase;diff --git a/apps/server/src/routers/lambda/__tests__/work.agentWork.test.ts b/apps/server/src/routers/lambda/__tests__/work.agentWork.test.tsnew file mode 100644index 00000000000..8669ff31d2c--- /dev/null+++ b/apps/server/src/routers/lambda/__tests__/work.agentWork.test.ts@@ -0,0 +1,155 @@+// @vitest-environment node+import { TRPCError } from '@trpc/server';+import { beforeEach, describe, expect, it, vi } from 'vitest';++vi.mock('@/database/core/db-adaptor', () => ({+ getServerDB: vi.fn(function () {+ return {};+ }),+}));++const mocks = vi.hoisted(() => ({+ createAgentWork: vi.fn(),+ deleteAgentWork: vi.fn(),+ resolveFile: vi.fn(),+ resolveRun: vi.fn(),+ updateAgentWork: vi.fn(),+}));++vi.mock('@/server/services/workRegistration', async (importOriginal) => ({+ ...(await importOriginal<object>()),+ resolveAgentWorkFile: mocks.resolveFile,+ resolveAgentWorkRun: mocks.resolveRun,+}));++const { AgentWorkError } = await import('@/database/models/work');+const { AgentWorkRunError } = await import('@/server/services/workRegistration');+const { workRouter } = await import('../work');++const run = { operationId: 'op_run', topicId: 'tpc_1', userId: 'user-1' };++const createCaller = () =>+ workRouter.createCaller({+ oidcAuth: { purpose: 'oidc', sub: 'user-1' },+ serverDB: {},+ userId: 'user-1',+ } as any);++const expectCode = async (promise: Promise<unknown>, code: TRPCError['code']) => {+ const error = await promise.catch((caught: unknown) => caught);+ expect(error).toBeInstanceOf(TRPCError);+ expect((error as TRPCError).code).toBe(code);+};++describe('workRouter — agent-created Works', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mocks.resolveRun.mockResolvedValue({+ run,+ workModel: {+ createAgentWork: mocks.createAgentWork,+ deleteAgentWork: mocks.deleteAgentWork,+ updateAgentWork: mocks.updateAgentWork,+ },+ workspaceId: 'ws_1',+ });+ mocks.resolveFile.mockResolvedValue({+ fileId: 'file_1',+ fileSize: 10,+ fileUrl: 'https://app.example.com/f/file_1',+ mimeType: 'application/pdf',+ });+ mocks.createAgentWork.mockResolvedValue({ id: 'work_1' });+ mocks.updateAgentWork.mockResolvedValue({ id: 'work_1' });+ });++ it('registers a file from the uploaded file row, not from caller-supplied metadata', async () => {+ await createCaller().createAgentWork({+ fileId: 'file_1',+ filePath: '/workspace/report.pdf',+ operationId: 'op_run',+ type: 'file',+ });++ expect(mocks.resolveRun).toHaveBeenCalledWith(+ expect.objectContaining({ operationId: 'op_run', userId: 'user-1' }),+ );+ expect(mocks.resolveFile).toHaveBeenCalledWith(+ expect.objectContaining({ fileId: 'file_1', userId: 'user-1', workspaceId: 'ws_1' }),+ );+ expect(mocks.createAgentWork).toHaveBeenCalledWith(run, {+ description: undefined,+ file: {+ fileId: 'file_1',+ filePath: '/workspace/report.pdf',+ fileSize: 10,+ fileUrl: 'https://app.example.com/f/file_1',+ mimeType: 'application/pdf',+ },+ title: undefined,+ type: 'file',+ });+ });++ it('requires a title for a link', async () => {+ await expectCode(+ createCaller().createAgentWork({+ operationId: 'op_run',+ type: 'link',+ url: 'https://preview.example.com',+ } as any),+ 'BAD_REQUEST',+ );+ expect(mocks.resolveRun).not.toHaveBeenCalled();+ });++ it('maps run and Work refusals onto tRPC error codes', async () => {+ mocks.resolveRun.mockRejectedValueOnce(+ new AgentWorkRunError('Operation has already ended', 409),+ );+ await expectCode(+ createCaller().updateAgentWork({ operationId: 'op_run', title: 'x', workId: 'work_1' }),+ 'CONFLICT',+ );++ mocks.updateAgentWork.mockRejectedValueOnce(new AgentWorkError('FORBIDDEN', 'automatic'));+ await expectCode(+ createCaller().updateAgentWork({ operationId: 'op_run', title: 'x', workId: 'work_1' }),+ 'FORBIDDEN',+ );+ });++ it('uploads nothing extra when an update names no file', async () => {+ await createCaller().updateAgentWork({+ description: 'Second draft',+ operationId: 'op_run',+ workId: 'work_1',+ });++ expect(mocks.resolveFile).not.toHaveBeenCalled();+ expect(mocks.updateAgentWork).toHaveBeenCalledWith(run, {+ description: 'Second draft',+ file: undefined,+ title: undefined,+ workId: 'work_1',+ });+ });++ it('deletes a Work through the run resolved from the operation', async () => {+ mocks.deleteAgentWork.mockResolvedValueOnce({ id: 'work_1', title: 'Wrong' });++ await expect(+ createCaller().deleteAgentWork({ operationId: 'op_run', workId: 'work_1' }),+ ).resolves.toEqual({ id: 'work_1', title: 'Wrong' });+ expect(mocks.resolveRun).toHaveBeenCalledWith(+ expect.objectContaining({ operationId: 'op_run' }),+ );+ expect(mocks.deleteAgentWork).toHaveBeenCalledWith(run, 'work_1');++ mocks.deleteAgentWork.mockRejectedValueOnce(new AgentWorkError('NOT_FOUND', 'missing'));+ await expectCode(+ createCaller().deleteAgentWork({ operationId: 'op_run', workId: 'work_2' }),+ 'NOT_FOUND',+ );+ });+});diff --git a/apps/server/src/routers/lambda/aiAgent/guards.ts b/apps/server/src/routers/lambda/aiAgent/guards.tsindex a4f76012cc7..cc0d6b68eb1 100644--- a/apps/server/src/routers/lambda/aiAgent/guards.ts+++ b/apps/server/src/routers/lambda/aiAgent/guards.ts@@ -9,7 +9,6 @@ import {assertCanUseTopicTargets,} from '@/server/routers/lambda/_helpers/conversationResourceGuard';import { assertCanUseWorkspaceAgent } from '@/server/routers/lambda/_helpers/workspaceAgentGuard';-import type { OperationCompletionShareVisitor } from '@/server/services/agentRuntime/CompletionLifecycle/types';export const resolveHeteroTopicWorkspace = async (params: {db: LobeChatDatabase;@@ -54,34 +53,6 @@ export const resolveHeteroTopicWorkspace = async (params: {return topic.workspaceId;};-/**- * The share visitor a hetero run on this topic belongs to, or `undefined` for- * an ordinary run. Read from the marker the dispatch stamped on the operation- * row, and trusted only when the topic really is that visitor's topic- * (`topics.senderId`). A visitor topic whose operation has no matching marker- * also resolves to `undefined`: its rows then stay hidden, which drops the- * run's output rather than exposing it to the wrong scope.- */-export const resolveHeteroRunShareVisitor = async (params: {- db: LobeChatDatabase;- operationId: string;- topicId: string;-}): Promise<OperationCompletionShareVisitor | undefined> => {- const { db, operationId, topicId } = params;- const [row] = await db- .select({ metadata: agentOperations.metadata, senderId: topics.senderId })- .from(agentOperations)- .innerJoin(topics, eq(topics.id, agentOperations.topicId))- .where(and(eq(agentOperations.id, operationId), eq(agentOperations.topicId, topicId)))- .limit(1);- if (!row?.senderId) return undefined;-- const marker = row.metadata?.agentShareVisitor as- Partial<OperationCompletionShareVisitor> | undefined;- if (!marker?.shareId || marker.visitorUserId !== row.senderId) return undefined;- return { shareId: marker.shareId, visitorUserId: marker.visitorUserId };-};-/*** Workspace `use` guard for operation-keyed endpoints: resolve the operation* row to its agent and run the same `use` guard. Operations without an agentdiff --git a/apps/server/src/routers/lambda/aiAgent/hetero.ts b/apps/server/src/routers/lambda/aiAgent/hetero.tsindex d153fd980e1..7a7675f189e 100644--- a/apps/server/src/routers/lambda/aiAgent/hetero.ts+++ b/apps/server/src/routers/lambda/aiAgent/hetero.ts@@ -37,12 +37,9 @@ import {HeteroOperationPrincipalError,resolveActiveHeteroOperationPrincipal,} from '@/server/services/heterogeneousAgent/operationPrincipal';+import { resolveHeteroRunShareVisitor } from '@/server/services/heterogeneousAgent/shareVisitor';-import {- assertCanUseOperationAgent,- resolveHeteroRunShareVisitor,- resolveHeteroTopicWorkspace,-} from './guards';+import { assertCanUseOperationAgent, resolveHeteroTopicWorkspace } from './guards';import {publishClaimedHeteroIntervention,submitHeteroInterventionAs,diff --git a/apps/server/src/routers/lambda/work.ts b/apps/server/src/routers/lambda/work.tsindex ce5482e4850..6441e5fc898 100644--- a/apps/server/src/routers/lambda/work.ts+++ b/apps/server/src/routers/lambda/work.ts@@ -14,20 +14,23 @@ import { withScopedPermission } from '@/business/server/trpc-middlewares/rbacPerimport { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceAuth';import { MessageModel } from '@/database/models/message';import { TopicModel } from '@/database/models/topic';-import { WorkModel } from '@/database/models/work';+import { AgentWorkError, WorkModel } from '@/database/models/work';import type { LobeChatDatabase } from '@/database/type';-import { router } from '@/libs/trpc/lambda';+import { heteroAuthedProcedure, router } from '@/libs/trpc/lambda';import { serverDatabase } from '@/libs/trpc/lambda/middleware';import { unpublishArtboardWork } from '@/server/services/artboard/publish/offline';import { createCanvasStorageService, isOwnCanvasManifestKey } from '@/server/services/canvas';import { deleteCanvas } from '@/server/services/canvas/delete';import {+ AgentWorkRunError,isBetterCodingExperienceEnabled,linkPushedPullRequests,linkTopicPullRequest,listTopicPullRequestsWithStatus,parsePullRequestUrl,registerShellWorksForLocalRun,+ resolveAgentWorkFile,+ resolveAgentWorkRun,resolveShellPullRequestLinking,setTopicPullRequestDismissed,} from '@/server/services/workRegistration';@@ -90,6 +93,7 @@ const cumulativeUsageSchema = z.object({// registration (see registerClientWorkFromIntent), and `z.object` strips// undeclared keys — omitting them here silently stores cost-less versions.const registerTaskSchema = z.object({+ agentEditable: z.boolean().nullable().optional(),agentId: z.string().nullable().optional(),cumulativeCost: z.number().nullable().optional(),cumulativeUsage: cumulativeUsageSchema.nullable().optional(),@@ -145,6 +149,7 @@ const registerCanvasSchema = z.object({const registerDocumentSchema = z.object({agentDocumentId: z.string().nullable().optional(),+ agentEditable: z.boolean().nullable().optional(),agentId: z.string().nullable().optional(),cumulativeCost: z.number().nullable().optional(),cumulativeUsage: cumulativeUsageSchema.nullable().optional(),@@ -160,7 +165,147 @@ const registerDocumentSchema = z.object({topicId: z.string().nullable().optional(),}) satisfies z.ZodType<RegisterDocumentWorkParams>;+// `lh work create|update`: an agent registering what it produced. The run's+// topic, agent and share scope come from `operationId`; file size, type and URL+// come from the uploaded file row.+const agentWorkTextSchema = {+ description: z.string().trim().max(2000).optional(),+ title: z.string().trim().min(1).max(200).optional(),+};+const agentWorkUrlSchema = z.string().trim().min(1).max(2048);++const createAgentWorkSchema = z.discriminatedUnion('type', [+ z.object({+ ...agentWorkTextSchema,+ fileId: z.string().min(1),+ filePath: z.string().trim().min(1).max(1024),+ operationId: z.string().min(1),+ type: z.literal('file'),+ }),+ z.object({+ ...agentWorkTextSchema,+ operationId: z.string().min(1),+ title: agentWorkTextSchema.title.unwrap(),+ type: z.literal('link'),+ url: agentWorkUrlSchema,+ }),+]);++const updateAgentWorkSchema = z.object({+ ...agentWorkTextSchema,+ fileId: z.string().min(1).optional(),+ operationId: z.string().min(1),+ workId: z.string().min(1),+});++const AGENT_WORK_ERROR_STATUS = {+ 401: 'UNAUTHORIZED',+ 403: 'FORBIDDEN',+ 404: 'NOT_FOUND',+ 409: 'CONFLICT',+} as const;++const toAgentWorkTRPCError = (error: unknown): never => {+ if (error instanceof AgentWorkRunError) {+ throw new TRPCError({+ cause: error,+ code: AGENT_WORK_ERROR_STATUS[error.status],+ message: error.message,+ });+ }+ if (error instanceof AgentWorkError) {+ throw new TRPCError({ cause: error, code: error.code, message: error.message });+ }+ throw error;+};++const agentWorkProcedure = heteroAuthedProcedure.use(serverDatabase);+export const workRouter = router({+ /** Register a file or link the running agent produced (`lh work create`). */+ createAgentWork: agentWorkProcedure+ .input(createAgentWorkSchema)+ .mutation(async ({ ctx, input }) => {+ try {+ const { run, workModel, workspaceId } = await resolveAgentWorkRun({+ auth: ctx,+ db: ctx.serverDB,+ operationId: input.operationId,+ userId: ctx.userId,+ });+ const text = { description: input.description, title: input.title };+ if (input.type === 'link') {+ return await workModel.createAgentWork(run, {+ ...text,+ title: input.title,+ type: 'link',+ url: input.url,+ });+ }++ const file = await resolveAgentWorkFile({+ db: ctx.serverDB,+ fileId: input.fileId,+ userId: run.userId,+ workspaceId,+ });+ return await workModel.createAgentWork(run, {+ ...text,+ file: { ...file, filePath: input.filePath },+ type: 'file',+ });+ } catch (error) {+ return toAgentWorkTRPCError(error);+ }+ }),++ /** Add a version to a Work the agent created (`lh work update`). */+ updateAgentWork: agentWorkProcedure+ .input(updateAgentWorkSchema)+ .mutation(async ({ ctx, input }) => {+ try {+ const { run, workModel, workspaceId } = await resolveAgentWorkRun({+ auth: ctx,+ db: ctx.serverDB,+ operationId: input.operationId,+ userId: ctx.userId,+ });+ const file = input.fileId+ ? await resolveAgentWorkFile({+ db: ctx.serverDB,+ fileId: input.fileId,+ userId: run.userId,+ workspaceId,+ })+ : undefined;+ return await workModel.updateAgentWork(run, {+ description: input.description,+ file,+ title: input.title,+ workId: input.workId,+ });+ } catch (error) {+ return toAgentWorkTRPCError(error);+ }+ }),++ /** Delete a Work the agent created by mistake (`lh work delete`). */+ deleteAgentWork: agentWorkProcedure+ .input(z.object({ operationId: z.string().min(1), workId: z.string().min(1) }))+ .mutation(async ({ ctx, input }) => {+ try {+ const { run, workModel } = await resolveAgentWorkRun({+ auth: ctx,+ db: ctx.serverDB,+ operationId: input.operationId,+ userId: ctx.userId,+ });+ return await workModel.deleteAgentWork(run, input.workId);+ } catch (error) {+ return toAgentWorkTRPCError(error);+ }+ }),+listByConversation: workProcedure.input(z.object({@@ -186,7 +331,7 @@ export const workRouter = router({originAgentId: z.string().nullable().optional(),provider: z.enum(WORK_SKILL_PROVIDERS).optional(),type: z- .enum(['task', 'document', 'external', 'file', 'canvas', 'artboard'])+ .enum(['task', 'document', 'external', 'file', 'collection', 'canvas', 'artboard']).nullable().optional(),visibility: z.enum(['private', 'public']).optional(),diff --git a/apps/server/src/services/aiAgent/pipeline/__tests__/toolDiscovery.shareGate.test.ts b/apps/server/src/services/aiAgent/pipeline/__tests__/toolDiscovery.shareGate.test.tsindex 11ebd3571e9..8ef2ce9578d 100644--- a/apps/server/src/services/aiAgent/pipeline/__tests__/toolDiscovery.shareGate.test.ts+++ b/apps/server/src/services/aiAgent/pipeline/__tests__/toolDiscovery.shareGate.test.ts@@ -1,4 +1,5 @@import { AgentDocumentsIdentifier } from '@lobechat/builtin-tool-agent-documents';+import { WorkIdentifier } from '@lobechat/builtin-tool-work';import type * as ModelBankModule from 'model-bank';import { beforeEach, describe, expect, it, vi } from 'vitest';@@ -310,7 +311,7 @@ describe('discoverTools - share gate blocks ungranted connectors early', () => {);});- it('enables Agent Documents for this run only after an explicit Share grant', async () => {+ it('enables Agent Documents only after an explicit Share grant, and Works always', async () => {await service.execAgent({agentId: 'agent-1',prompt: 'Create a document',@@ -325,6 +326,7 @@ describe('discoverTools - share gate blocks ungranted connectors early', () => {expect(mockCreateServerAgentToolsEngine).toHaveBeenCalledTimes(1);expect(mockCreateServerAgentToolsEngine.mock.calls[0][1].agentConfig.plugins).toEqual([AgentDocumentsIdentifier,+ WorkIdentifier,]);vi.clearAllMocks();@@ -347,7 +349,11 @@ describe('discoverTools - share gate blocks ungranted connectors early', () => {},});- expect(mockCreateServerAgentToolsEngine.mock.calls[0][1].agentConfig.plugins).toEqual([]);+ expect(mockCreateServerAgentToolsEngine.mock.calls[0][1].agentConfig.plugins).toEqual([+ WorkIdentifier,+ ]);+ // An always-on builtin is never looked up as a connector.+ expect(mockResolveByIdentifiers).not.toHaveBeenCalled();});it('reads attached file types through the exact share visitor scope', async () => {diff --git a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/prepare.parallelReads.test.ts b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/prepare.parallelReads.test.tsindex 7388f8c5089..4ebc1b029d5 100644--- a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/prepare.parallelReads.test.ts+++ b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/prepare.parallelReads.test.ts@@ -303,7 +303,7 @@ describe('prepareHeteroRun — overlapping reads', () => {expect(credsGet).not.toHaveBeenCalled();expect(mocks.signHeteroOperationJWT).toHaveBeenCalledWith(expect.objectContaining({- capabilities: ['hetero:ingest', 'hetero:finish', 'hetero:intervention:read'],+ capabilities: ['hetero:ingest', 'hetero:finish', 'hetero:intervention:read', 'work:write'],}),);});diff --git a/apps/server/src/services/aiAgent/pipeline/heteroOperationCapabilities.test.ts b/apps/server/src/services/aiAgent/pipeline/heteroOperationCapabilities.test.tsindex e0645f50a0c..0d7d23b505e 100644--- a/apps/server/src/services/aiAgent/pipeline/heteroOperationCapabilities.test.ts+++ b/apps/server/src/services/aiAgent/pipeline/heteroOperationCapabilities.test.ts@@ -54,6 +54,7 @@ describe('heteroOperationCapabilities', () => {'hetero:ingest','hetero:finish','hetero:intervention:read',+ 'work:write',]);expect(heteroOperationCapabilities(undefined)).not.toContain('goal:manage');});@@ -69,6 +70,15 @@ describe('heteroOperationCapabilities', () => {it('keeps acceptance evidence out of a run with no Task', () => {expect(heteroOperationCapabilities('fix the build', {})).not.toContain('acceptance:evidence');});++ it.each([+ ['an ordinary run', {}],+ ['a Task run', { taskId: 'task_1' }],+ ['a Channel dispatch', { channel: true }],+ ['a user turn', { userTurn: true }],+ ])('lets %s register its own Works', (_, options) => {+ expect(heteroOperationCapabilities('make the deck', options)).toContain('work:write');+ });});describe('heteroOperationCapabilities for a share visitor', () => {@@ -76,11 +86,12 @@ describe('heteroOperationCapabilities for a share visitor', () => {['a /goal prompt', '/goal ship the report', { userTurn: true }],['a task', 'do the step', { taskId: 'task_1', userTurn: true }],['a channel', 'read the discussion', { channel: true, ownerBotTurn: true }],- ])('grants only the run callbacks for %s', (_, prompt, options) => {+ ])('grants only the run callbacks and its own Works for %s', (_, prompt, options) => {expect(heteroOperationCapabilities(prompt, { ...options, shareVisitor: true })).toEqual(['hetero:ingest','hetero:finish','hetero:intervention:read',+ 'work:write',]);});});diff --git a/apps/server/src/services/aiAgent/pipeline/heteroOperationCapabilities.ts b/apps/server/src/services/aiAgent/pipeline/heteroOperationCapabilities.tsindex 78a757a55cd..688bc4370c3 100644--- a/apps/server/src/services/aiAgent/pipeline/heteroOperationCapabilities.ts+++ b/apps/server/src/services/aiAgent/pipeline/heteroOperationCapabilities.ts@@ -32,6 +32,11 @@ import type { HeteroOperationCapability } from '@/libs/trpc/utils/internalJwt';* the token is the only identity that can reach it. Only a Task run has a* round to file into.*+ * `work:write` lets every run register the files and links it produced as Work+ * cards under its reply (`lh work create|update`). The Work lands in the run's+ * own topic; a share visitor's run included, whose Works stay fenced to that+ * visitor topic exactly like the ones its completion scan registers.+ ** Renewal copies the minted claims, so a run never gains either later.*/export const heteroOperationCapabilities = (@@ -51,7 +56,7 @@ export const heteroOperationCapabilities = (} = {},): HeteroOperationCapability[] =>options.shareVisitor- ? ['hetero:ingest', 'hetero:finish', 'hetero:intervention:read']+ ? ['hetero:ingest', 'hetero:finish', 'hetero:intervention:read', 'work:write']: ['hetero:ingest',...(options.channel@@ -65,4 +70,5 @@ export const heteroOperationCapabilities = (? (['goal:manage'] as const): []),...(options.taskId ? (['acceptance:evidence'] as const) : []),+ 'work:write',];diff --git a/apps/server/src/services/aiAgent/pipeline/toolDiscovery/index.ts b/apps/server/src/services/aiAgent/pipeline/toolDiscovery/index.tsindex 5a5c805bcb8..20af491520d 100644--- a/apps/server/src/services/aiAgent/pipeline/toolDiscovery/index.ts+++ b/apps/server/src/services/aiAgent/pipeline/toolDiscovery/index.ts@@ -9,7 +9,11 @@ import {SELF_FEEDBACK_INTENT_IDENTIFIER,shouldExposeSelfFeedbackIntentTool,} from '@lobechat/builtin-tool-self-iteration';-import { getUnavailableBuiltinToolIds, runtimeManagedToolIds } from '@lobechat/builtin-tools';+import {+ AGENT_SHARE_IMPLIED_BUILTIN_IDENTIFIERS,+ getUnavailableBuiltinToolIds,+ runtimeManagedToolIds,+} from '@lobechat/builtin-tools';import { getFeatureDisabledToolIds } from '@lobechat/builtin-tools/featureGates';import type {AgentGroupConfig,@@ -277,8 +281,12 @@ export const discoverTools = async (: startToolReads(deps, {agentConfig,attachedFileIds,+ // The builtins a share run always gets are never connectors; leaving+ // them out keeps an ungranted share from reading connector rows.candidateIds: injectedConnectorCandidateIds.filter(- (identifier) => !boundConnectorIds.has(identifier),+ (identifier) =>+ !boundConnectorIds.has(identifier) &&+ !AGENT_SHARE_IMPLIED_BUILTIN_IDENTIFIERS.has(identifier),),// Bound eval tools must not auto-discover unrelated credential-bearing// connectors. This limits reads only; progressive activation remains enabled.diff --git a/apps/server/src/services/aiAgent/shareGate/README.md b/apps/server/src/services/aiAgent/shareGate/README.mdindex 65b34a8a71b..db14f25ab89 100644--- a/apps/server/src/services/aiAgent/shareGate/README.md+++ b/apps/server/src/services/aiAgent/shareGate/README.md@@ -207,3 +207,25 @@ absence of a known exploit.a creator who opens a skill opens that skill's instructions, and that isthe premise of Agent Share, not a hole in it. The gate's job is to executethe grant exactly, not to second-guess which skills a creator should share.++- `lobe-work`: the one builtin a visitor run gets WITHOUT a creator grant+ (`AGENT_SHARE_IMPLIED_BUILTIN_IDENTIFIERS`): `resolveEffectiveShareToolGrants`+ implies it, `getShareGrantActivatedPluginIds` enables it, and+ `filterPluginsByShareGate` keeps it, so the owner's picker shows no toggle+ for it. It only registers what the run produced as Work cards:++ 1. the run (operation, topic, tool call, assistant message) comes from the+ execution context, never from model arguments;+ 2. writes go through `WorkModel` under the share scope pinned to the+ visitor topic (`resolveRunWorkAccessScope`), so the Works never reach the+ creator's ordinary lists; a visitor run without a topic is refused;+ 3. `updateWork` / `deleteWork` reach only Works this conversation created+ through the tool or `lh work` (`agentEditable`), never ones collected+ automatically or made in another conversation;+ 4. collection images must be generated images or run outputs of the run's+ account (`resolveAgentWorkCollectionItems`), and in a visitor run each image+ must also appear in a message of the visitor topic (`visitorTopicId`), so+ a guessed id of another creator image is refused as not found.++ Its implied grant is added after the activator check, so it never implies+ `lobe-activator` on its own.diff --git a/apps/server/src/services/aiAgent/shareGate/grants.test.ts b/apps/server/src/services/aiAgent/shareGate/grants.test.tsindex ade31c99586..2877ef99962 100644--- a/apps/server/src/services/aiAgent/shareGate/grants.test.ts+++ b/apps/server/src/services/aiAgent/shareGate/grants.test.ts@@ -3,6 +3,7 @@ import { AgentDocumentsIdentifier } from '@lobechat/builtin-tool-agent-documentsimport { AuvIdentifier } from '@lobechat/builtin-tool-auv';import { CloudSandboxManifest } from '@lobechat/builtin-tool-cloud-sandbox';import { LobeAgentApiName, LobeAgentIdentifier } from '@lobechat/builtin-tool-lobe-agent';+import { WorkIdentifier } from '@lobechat/builtin-tool-work';import { describe, expect, it } from 'vitest';import {@@ -27,6 +28,12 @@ describe('filterPluginsByShareGate', () => {]);});+ it('keeps the Works tool without any grant', () => {+ expect(filterPluginsByShareGate([WorkIdentifier, 'web-search'], buildGate())).toEqual([+ WorkIdentifier,+ ]);+ });+it('exposes no tools when the allowlist is missing or empty', () => {expect(filterPluginsByShareGate(['web-search'], buildGate())).toEqual([]);expect(filterPluginsByShareGate(['web-search'], buildGate({ toolGrants: [] }))).toEqual([]);@@ -82,12 +89,21 @@ describe('filterSkillsByShareGate', () => {describe('getShareGrantActivatedPluginIds', () => {it('activates Agent Documents only after the owner grants it for this Share', () => {- expect(getShareGrantActivatedPluginIds(buildGate())).toEqual([]);+ expect(getShareGrantActivatedPluginIds(buildGate())).not.toContain(AgentDocumentsIdentifier);+ expect(+ getShareGrantActivatedPluginIds(+ buildGate({ toolGrants: [{ identifier: AgentDocumentsIdentifier }] }),+ ),+ ).toContain(AgentDocumentsIdentifier);+ });++ it('activates the Works tool in every visitor run, granted or not', () => {+ expect(getShareGrantActivatedPluginIds(buildGate())).toEqual([WorkIdentifier]);expect(getShareGrantActivatedPluginIds(buildGate({ toolGrants: [{ identifier: AgentDocumentsIdentifier }] }),),- ).toEqual([AgentDocumentsIdentifier]);+ ).toEqual([AgentDocumentsIdentifier, WorkIdentifier]);});});@@ -142,6 +158,7 @@ describe('resolveEffectiveShareToolGrants — lobe-activator', () => {});it('does not imply the activator when the share grants no tool', () => {+ // The implied Works grant is enabled directly; it never needs the activator.expect(resolveEffectiveShareToolGrants({}).has(LobeActivatorIdentifier)).toBe(false);// A skill-only share already has lobe-skills to load what it granted.expect(@@ -168,3 +185,22 @@ describe('resolveEffectiveShareToolGrants — lobe-activator', () => {expect(alone.has(LobeActivatorIdentifier)).toBe(false);});});++describe('resolveEffectiveShareToolGrants — lobe-work', () => {+ it('grants the Works tool to every share, whatever the owner picked', () => {+ expect(resolveEffectiveShareToolGrants({}).get(WorkIdentifier)).toBe('all');+ expect(+ resolveEffectiveShareToolGrants({ toolGrants: [{ identifier: 'mcp-github' }] }).get(+ WorkIdentifier,+ ),+ ).toBe('all');+ });++ it('widens a stored per-API Works entry to the whole tool', () => {+ expect(+ resolveEffectiveShareToolGrants({+ toolGrants: [{ apis: ['createWork'], identifier: WorkIdentifier }],+ }).get(WorkIdentifier),+ ).toBe('all');+ });+});diff --git a/apps/server/src/services/aiAgent/shareGate/grants.ts b/apps/server/src/services/aiAgent/shareGate/grants.tsindex 6a095506624..da0ce8be19c 100644--- a/apps/server/src/services/aiAgent/shareGate/grants.ts+++ b/apps/server/src/services/aiAgent/shareGate/grants.ts@@ -2,6 +2,7 @@ import { ActivatorApiName, LobeActivatorIdentifier } from '@lobechat/builtin-tooimport { AgentDocumentsIdentifier } from '@lobechat/builtin-tool-agent-documents';import { CloudSandboxManifest } from '@lobechat/builtin-tool-cloud-sandbox';import { SkillsIdentifier } from '@lobechat/builtin-tool-skills';+import { AGENT_SHARE_IMPLIED_BUILTIN_IDENTIFIERS } from '@lobechat/builtin-tools';import {hasShareToolGrant,resolveShareAllowedSkillIds,@@ -27,9 +28,12 @@ export const filterPluginsByShareGate = (pluginIds: string[], gate: AgentShareGaconst grants = resolveShareToolGrants(gate.shareConfig.toolGrants);// Device builtins (a pinned Computer Use, say) follow the device grant, not- // the tool picker, exactly as `applyShareGateToToolSet` decides them.+ // the tool picker, exactly as `applyShareGateToToolSet` decides them. The+ // implied builtins need no grant (see `resolveEffectiveShareToolGrants`).return pluginIds.filter((id) =>- isShareDeviceBuiltin(id) ? !!gate.canUseDevice : hasShareToolGrant(grants, id),+ isShareDeviceBuiltin(id)+ ? !!gate.canUseDevice+ : AGENT_SHARE_IMPLIED_BUILTIN_IDENTIFIERS.has(id) || hasShareToolGrant(grants, id),);};@@ -56,11 +60,18 @@ export const filterSkillsByShareGate = (skillIds: string[], gate: AgentShareGate* `agentConfig.plugins`. Adding it here only after an explicit Share grant* lets the picker act as that opt-in for visitor runs while keeping the* default-closed behavior. The final tool-set gate still narrows its APIs.+ *+ * The implied builtins (`lobe-work`) are on in every visitor run with no+ * grant at all: a visitor's Works stay in their own topic (see+ * {@link resolveEffectiveShareToolGrants}).*/export const getShareGrantActivatedPluginIds = (gate: AgentShareGate): string[] => {const grants = resolveShareToolGrants(gate.shareConfig.toolGrants);- return hasShareToolGrant(grants, AgentDocumentsIdentifier) ? [AgentDocumentsIdentifier] : [];+ return [+ ...(hasShareToolGrant(grants, AgentDocumentsIdentifier) ? [AgentDocumentsIdentifier] : []),+ ...AGENT_SHARE_IMPLIED_BUILTIN_IDENTIFIERS,+ ];};/**@@ -142,6 +153,11 @@ export const hasShareSkillAuthorization = (permissions: ShareDataToolPermissions* `applyShareGateToToolSet`. Always written as `activateTools` only, so a* stored or hand-edited `lobe-activator` entry can never widen it to the* runtime's unlisted `activateSkill` method.+ * - `lobe-work` (every {@link AGENT_SHARE_IMPLIED_BUILTIN_IDENTIFIERS} entry),+ * on in every visitor run: it registers what the visitor run produced as+ * Works fenced to the visitor topic, never the creator's lists. Added+ * after the activator check, so it alone never implies the activator: it is+ * enabled directly (`getShareGrantActivatedPluginIds`), not activated.** Every gate that asks "did the creator grant this identifier" must go through* here, or the tool passes one layer and is rejected by the next.@@ -158,5 +174,7 @@ export const resolveEffectiveShareToolGrants = (if (hasShareSkillAuthorization(permissions)) grants.set(SkillsIdentifier, 'all');+ for (const identifier of AGENT_SHARE_IMPLIED_BUILTIN_IDENTIFIERS) grants.set(identifier, 'all');+return grants;};diff --git a/apps/server/src/services/heterogeneousAgent/shareVisitor.ts b/apps/server/src/services/heterogeneousAgent/shareVisitor.tsnew file mode 100644index 00000000000..b193497bf3c--- /dev/null+++ b/apps/server/src/services/heterogeneousAgent/shareVisitor.ts@@ -0,0 +1,33 @@+import { and, eq } from 'drizzle-orm';++import { agentOperations, topics } from '@/database/schemas';+import type { LobeChatDatabase } from '@/database/type';+import type { OperationCompletionShareVisitor } from '@/server/services/agentRuntime/CompletionLifecycle/types';++/**+ * The share visitor a hetero run on this topic belongs to, or `undefined` for+ * an ordinary run. Read from the marker the dispatch stamped on the operation+ * row, and trusted only when the topic really is that visitor's topic+ * (`topics.senderId`). A visitor topic whose operation has no matching marker+ * also resolves to `undefined`: its rows then stay hidden, which drops the+ * run's output rather than exposing it to the wrong scope.+ */+export const resolveHeteroRunShareVisitor = async (params: {+ db: LobeChatDatabase;+ operationId: string;+ topicId: string;+}): Promise<OperationCompletionShareVisitor | undefined> => {+ const { db, operationId, topicId } = params;+ const [row] = await db+ .select({ metadata: agentOperations.metadata, senderId: topics.senderId })+ .from(agentOperations)+ .innerJoin(topics, eq(topics.id, agentOperations.topicId))+ .where(and(eq(agentOperations.id, operationId), eq(agentOperations.topicId, topicId)))+ .limit(1);+ if (!row?.senderId) return undefined;++ const marker = row.metadata?.agentShareVisitor as+ Partial<OperationCompletionShareVisitor> | undefined;+ if (!marker?.shareId || marker.visitorUserId !== row.senderId) return undefined;+ return { shareId: marker.shareId, visitorUserId: marker.visitorUserId };+};diff --git a/apps/server/src/services/toolExecution/__tests__/builtin.test.ts b/apps/server/src/services/toolExecution/__tests__/builtin.test.tsindex 14c78ff7b13..88494d7eadd 100644--- a/apps/server/src/services/toolExecution/__tests__/builtin.test.ts+++ b/apps/server/src/services/toolExecution/__tests__/builtin.test.ts@@ -44,6 +44,7 @@ vi.mock('@/server/services/market', () => ({// below can exercise the per-API data-tool rules.vi.mock('@lobechat/builtin-tools', () => ({AGENT_SHARE_ALLOWED_BUILTIN_IDENTIFIERS: new Set(['lobe-user-memory']),+ AGENT_SHARE_IMPLIED_BUILTIN_IDENTIFIERS: new Set<string>(),isBuiltinToolIdentifier: (id: string) =>['lobe-notebook', 'lobe-task', 'lobe-user-memory'].includes(id),builtinTools: [diff --git a/apps/server/src/services/toolExecution/serverRuntimes/index.ts b/apps/server/src/services/toolExecution/serverRuntimes/index.tsindex 0f7724d97e9..1159ab2e05f 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/index.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/index.ts@@ -59,6 +59,7 @@ import { videoGenerationRuntime } from './videoGeneration';import { webBrowsingRuntime } from './webBrowsing';import { webhookRuntime } from './webhook';import { webOnboardingRuntime } from './webOnboarding';+import { workRuntime } from './work';/*** Registry of server runtime factories by identifier@@ -78,6 +79,7 @@ const registerRuntimes = (runtimes: ServerRuntimeRegistration[]) => {registerRuntimes([mcpEventsRuntime,webhookRuntime,+ workRuntime,channelRuntime,acceptanceEvidenceRuntime,auvRuntime,diff --git a/apps/server/src/services/toolExecution/serverRuntimes/work.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/work.test.tsnew file mode 100644index 00000000000..dfb68ae8a09--- /dev/null+++ b/apps/server/src/services/toolExecution/serverRuntimes/work.test.ts@@ -0,0 +1,297 @@+// @vitest-environment node+import { WorkIdentifier } from '@lobechat/builtin-tool-work';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import type * as AgentWorkModel from '@/database/models/work/agentWork';+import type * as AgentWorkService from '@/server/services/workRegistration/agentWork';+import type * as ShareWorkScope from '@/server/services/workRegistration/shareWorkScope';++import type { ToolExecutionContext } from '../types';+import { getServerRuntime, hasServerRuntime } from './index';+import { workRuntime } from './work';++const mocks = vi.hoisted(() => ({+ construct: vi.fn(),+ createAgentWork: vi.fn(),+ deleteAgentWork: vi.fn(),+ resolveCollection: vi.fn(),+ updateAgentWork: vi.fn(),+}));++vi.mock('@/database/models/work', async () => {+ const { AgentWorkError } = await vi.importActual<typeof AgentWorkModel>(+ '@/database/models/work/agentWork',+ );+ return {+ AgentWorkError,+ WorkModel: class {+ constructor(...args: unknown[]) {+ mocks.construct(...args);+ }+ createAgentWork = mocks.createAgentWork;+ deleteAgentWork = mocks.deleteAgentWork;+ updateAgentWork = mocks.updateAgentWork;+ },+ };+});++vi.mock('@/server/services/workRegistration', async () => {+ const agentWork = await vi.importActual<typeof AgentWorkService>(+ '@/server/services/workRegistration/agentWork',+ );+ const scope = await vi.importActual<typeof ShareWorkScope>(+ '@/server/services/workRegistration/shareWorkScope',+ );+ return {+ AgentWorkRunError: agentWork.AgentWorkRunError,+ parseCollectionImageRef: agentWork.parseCollectionImageRef,+ resolveAgentWorkCollectionItems: mocks.resolveCollection,+ resolveRunWorkAccessScope: scope.resolveRunWorkAccessScope,+ };+});++const { AgentWorkError } = await import('@/database/models/work');+const { AgentWorkRunError } = await import('@/server/services/workRegistration');++const context: ToolExecutionContext = {+ agentId: 'agent',+ assistantMessageId: 'msg-1',+ operationId: 'op-step',+ rootOperationId: 'op-root',+ serverDB: {} as never,+ threadId: null,+ toolCallId: 'call-1',+ toolManifestMap: {},+ topicId: 'topic',+ userId: 'user',+ workspaceId: 'workspace',+};++const run = {+ agentId: 'agent',+ messageId: 'msg-1',+ operationId: 'op-root',+ threadId: null,+ toolCallId: 'call-1',+ toolIdentifier: 'lobe-work',+ topicId: 'topic',+ userId: 'user',+};++const collectionItems = [+ { fileId: 'file_a', mimeType: 'image/png', url: 'https://cdn/a.png' },+ { caption: 'Night', fileId: 'file_b', mimeType: 'image/png', url: 'https://cdn/b.png' },+];++beforeEach(() => {+ vi.clearAllMocks();+ mocks.resolveCollection.mockResolvedValue(collectionItems);+});++describe('workRuntime', () => {+ it('is registered under lobe-work', () => {+ expect(hasServerRuntime(WorkIdentifier)).toBe(true);+ expect(workRuntime.identifier).toBe('lobe-work');+ expect(getServerRuntime(WorkIdentifier, context)).toBeDefined();+ });++ it('creates a collection from the run context, resolving images and the cover', async () => {+ mocks.createAgentWork.mockResolvedValue({+ id: 'wk_1',+ title: 'Covers',+ type: 'collection',+ url: 'https://cdn/b.png',+ });++ const result = await workRuntime.factory(context).createWork({+ coverImage: 'https://app.lobehub.com/f/file_b',+ items: [{ image: 'file_a' }, { caption: 'Night', image: '/f/file_b' }],+ title: 'Covers',+ type: 'collection',+ });++ expect(mocks.construct).toHaveBeenCalledWith(context.serverDB, 'user', 'workspace', undefined);+ expect(mocks.resolveCollection).toHaveBeenCalledWith({+ db: context.serverDB,+ items: [{ image: 'file_a' }, { caption: 'Night', image: '/f/file_b' }],+ userId: 'user',+ workspaceId: 'workspace',+ });+ expect(mocks.createAgentWork).toHaveBeenCalledWith(run, {+ coverFileId: 'file_b',+ description: undefined,+ items: collectionItems,+ title: 'Covers',+ type: 'collection',+ });+ expect(result).toMatchObject({+ state: { work: { imageCount: 2, title: 'Covers', type: 'collection', workId: 'wk_1' } },+ success: true,+ });+ });++ it('creates a link Work', async () => {+ mocks.createAgentWork.mockResolvedValue({+ id: 'wk_2',+ resourceType: 'link',+ title: 'Site',+ type: 'external',+ url: 'https://example.com/',+ });++ const result = await workRuntime+ .factory(context)+ .createWork({ title: 'Site', type: 'link', url: 'https://example.com' });++ expect(mocks.createAgentWork).toHaveBeenCalledWith(run, {+ description: undefined,+ title: 'Site',+ type: 'link',+ url: 'https://example.com',+ });+ expect(result.state).toEqual({+ work: { title: 'Site', type: 'link', url: 'https://example.com/', workId: 'wk_2' },+ });+ });++ it('reports a renamed file Work as a file, not a link', async () => {+ mocks.updateAgentWork.mockResolvedValue({+ id: 'wk_3',+ resourceType: 'file',+ title: 'Q3 report',+ type: 'file',+ url: 'https://app.example.com/f/file_r',+ });++ const result = await workRuntime+ .factory(context)+ .updateWork({ title: 'Q3 report', workId: 'wk_3' });++ expect(result.state).toMatchObject({ work: { type: 'file', workId: 'wk_3' } });+ });++ it('replaces the collection on update and leaves it alone on a title-only update', async () => {+ mocks.updateAgentWork.mockResolvedValue({ id: 'wk_1', title: 'Covers v2', type: 'collection' });+ const runtime = workRuntime.factory(context);++ await runtime.updateWork({ items: [{ image: 'file_a' }], workId: 'wk_1' });+ expect(mocks.updateAgentWork).toHaveBeenLastCalledWith(run, {+ description: undefined,+ collection: { items: collectionItems },+ title: undefined,+ workId: 'wk_1',+ });++ await runtime.updateWork({ title: 'Covers v2', workId: 'wk_1' });+ expect(mocks.resolveCollection).toHaveBeenCalledTimes(1);+ expect(mocks.updateAgentWork).toHaveBeenLastCalledWith(run, {+ description: undefined,+ collection: undefined,+ title: 'Covers v2',+ workId: 'wk_1',+ });+ });++ it('deletes a Work', async () => {+ mocks.deleteAgentWork.mockResolvedValue({ id: 'wk_1', title: 'Covers' });++ const result = await workRuntime.factory(context).deleteWork({ workId: 'wk_1' });++ expect(mocks.deleteAgentWork).toHaveBeenCalledWith(run, 'wk_1');+ expect(result.state).toEqual({ deleted: { title: 'Covers', workId: 'wk_1' } });+ });++ it('maps model and resolver refusals to stable codes', async () => {+ const runtime = workRuntime.factory(context);++ mocks.deleteAgentWork.mockRejectedValueOnce(new AgentWorkError('NOT_FOUND', 'Work not found'));+ expect((await runtime.deleteWork({ workId: 'wk_x' })).error).toEqual({+ message: 'Work not found',+ type: 'not_found',+ });++ mocks.updateAgentWork.mockRejectedValueOnce(+ new AgentWorkError('BAD_REQUEST', 'Only a collection'),+ );+ expect((await runtime.updateWork({ title: 'x', workId: 'wk_1' })).error?.type).toBe(+ 'invalid_input',+ );++ mocks.resolveCollection.mockRejectedValueOnce(+ new AgentWorkRunError('Image file_z not found', 404),+ );+ expect(+ (await runtime.createWork({ items: [{ image: 'file_z' }], title: 'x', type: 'collection' }))+ .error?.type,+ ).toBe('not_found');++ // A cover that is not a LobeHub file link is refused by the ref parser.+ expect(+ (+ await runtime.createWork({+ coverImage: 'https://example.com/x.png',+ items: [{ image: 'file_a' }],+ title: 'x',+ type: 'collection',+ })+ ).error?.type,+ ).toBe('not_found');+ });++ it("writes a share visitor's Works under the visitor topic's share scope", async () => {+ mocks.deleteAgentWork.mockResolvedValue({ id: 'wk_1', title: null });++ await workRuntime+ .factory({+ ...context,+ agentShareVisitor: { agentId: 'agent', shareId: 'share-1', visitorUserId: 'visitor' },+ })+ .deleteWork({ workId: 'wk_1' });++ const accessScope = mocks.construct.mock.calls[0][3];+ expect(accessScope).toBeDefined();+ expect(JSON.stringify(accessScope)).toContain('share-1');+ expect(JSON.stringify(accessScope)).toContain('topic');+ });++ it('maps a cover named by generationId to that image file', async () => {+ mocks.resolveCollection.mockResolvedValueOnce([+ { fileId: 'file_a', mimeType: 'image/png', url: 'https://app.example.com/f/file_a' },+ { fileId: 'file_b', mimeType: 'image/png', url: 'https://app.example.com/f/file_b' },+ ]);++ await workRuntime.factory(context).createWork({+ coverImage: 'gen_2',+ items: [{ image: 'gen_1' }, { image: 'gen_2' }],+ title: 'Cats',+ type: 'collection',+ });++ expect(mocks.createAgentWork).toHaveBeenCalledWith(+ run,+ expect.objectContaining({ coverFileId: 'file_b' }),+ );+ });++ it("checks a share visitor's collection images against the visitor conversation", async () => {+ await workRuntime+ .factory({+ ...context,+ agentShareVisitor: { agentId: 'agent', shareId: 'share-1', visitorUserId: 'visitor' },+ })+ .createWork({ items: [{ image: 'file_a' }], title: 'Covers', type: 'collection' });++ expect(mocks.resolveCollection).toHaveBeenCalledWith(+ expect.objectContaining({ visitorTopicId: context.topicId }),+ );+ });++ it('refuses every call outside a conversation instead of failing dispatch', async () => {+ const runtime = workRuntime.factory({ ...context, topicId: undefined });++ const result = await runtime.createWork({ title: 'Site', type: 'link', url: 'https://x.dev' });++ expect(result).toMatchObject({ error: { type: 'unavailable' }, success: false });+ expect(mocks.construct).not.toHaveBeenCalled();+ });+});diff --git a/apps/server/src/services/toolExecution/serverRuntimes/work.ts b/apps/server/src/services/toolExecution/serverRuntimes/work.tsnew file mode 100644index 00000000000..8271d5c5e7d--- /dev/null+++ b/apps/server/src/services/toolExecution/serverRuntimes/work.ts@@ -0,0 +1,184 @@+import { WorkIdentifier, type WorkSummary } from '@lobechat/builtin-tool-work';+import {+ WorkExecutionRuntime,+ WorkToolError,+ type WorkToolService,+} from '@lobechat/builtin-tool-work/executionRuntime';+import type { AgentWorkRunContext, WorkItem } from '@lobechat/types';++import { AgentWorkError, WorkModel } from '@/database/models/work';+import {+ AgentWorkRunError,+ parseCollectionImageRef,+ resolveAgentWorkCollectionItems,+ resolveRunWorkAccessScope,+} from '@/server/services/workRegistration';++import type { ToolExecutionContext } from '../types';+import type { ServerRuntimeRegistration } from './types';++const MODEL_ERROR_CODES = {+ BAD_REQUEST: 'invalid_input',+ CONFLICT: 'conflict',+ FORBIDDEN: 'forbidden',+ NOT_FOUND: 'not_found',+} as const;++const RUN_ERROR_CODES = {+ 401: 'unavailable',+ 403: 'forbidden',+ 404: 'not_found',+ 409: 'conflict',+} as const;++/** Translate the model's and the resolver's refusals into the tool's stable codes. */+const toToolError = (error: unknown): unknown => {+ if (error instanceof AgentWorkError)+ return new WorkToolError(MODEL_ERROR_CODES[error.code], error.message);+ if (error instanceof AgentWorkRunError)+ return new WorkToolError(RUN_ERROR_CODES[error.status], error.message);+ return error;+};++const guarded =+ <A extends unknown[], R>(fn: (...args: A) => Promise<R>) =>+ async (...args: A): Promise<R> => {+ try {+ return await fn(...args);+ } catch (error) {+ throw toToolError(error);+ }+ };++const summarize = (work: WorkItem, imageCount?: number): WorkSummary => ({+ ...(imageCount === undefined ? {} : { imageCount }),+ title: work.title ?? null,+ // An external Work this tool writes is always a link; a `file` Work is one the+ // CLI created in this conversation that the agent renamed here.+ type: work.type === 'collection' || work.type === 'file' ? work.type : 'link',+ url: work.url ?? null,+ workId: work.id,+});++/**+ * The `lobe-work` tools: the agent registers collections and links it produced+ * as Works of this run. The run (conversation, operation, tool call) comes+ * from the execution context, never from the model, and the agent can change+ * only the Works it created in this conversation (`findAgentManagedWork`).+ *+ * A share visitor's run writes under the share scope pinned to the visitor's+ * topic, so its Works stay out of the creator's ordinary lists.+ */+export const createWorkToolService = (context: ToolExecutionContext): WorkToolService => {+ const { agentShareVisitor, serverDB: db, topicId, userId, workspaceId } = context;+ const operationId = context.rootOperationId ?? context.operationId;+ if (!db || !userId || !topicId || !operationId) {+ throw new WorkToolError(+ 'unavailable',+ 'Works can be registered only inside a conversation run',+ );+ }++ const accessScope = resolveRunWorkAccessScope({ shareVisitor: agentShareVisitor, topicId });+ // Only a share run without a topic resolves to null, and the check above+ // already requires a topic; keep the refusal so a scope change cannot leak+ // a visitor's Work into the creator's lists.+ if (accessScope === null) {+ throw new WorkToolError('unavailable', 'This shared conversation cannot register Works');+ }++ const workModel = new WorkModel(db, userId, workspaceId, accessScope);+ const run: AgentWorkRunContext = {+ agentId: context.agentId ?? null,+ messageId: context.assistantMessageId ?? null,+ operationId,+ threadId: context.threadId ?? null,+ toolCallId: context.toolCallId ?? null,+ toolIdentifier: WorkIdentifier,+ topicId,+ userId,+ };++ const resolveCollection = async (+ items: { caption?: string; image: string }[],+ coverImage?: string,+ ) => {+ const resolved = await resolveAgentWorkCollectionItems({+ db,+ items,+ userId,+ visitorTopicId: agentShareVisitor ? topicId : undefined,+ workspaceId,+ });+ // The cover names one of the items the same way; map it to that item's+ // file. A cover outside the list stays as named and is refused as such.+ const coverRef = coverImage ? parseCollectionImageRef(coverImage) : undefined;+ const coverIndex = coverRef+ ? items.findIndex(({ image }) => parseCollectionImageRef(image) === coverRef)+ : -1;+ const coverFileId = coverIndex >= 0 ? resolved[coverIndex].fileId : coverRef;+ return { ...(coverFileId ? { coverFileId } : {}), items: resolved };+ };++ return {+ create: guarded(async (args) => {+ if (args.type === 'link') {+ const work = await workModel.createAgentWork(run, {+ description: args.description,+ title: args.title,+ type: 'link',+ url: args.url!,+ });+ return summarize(work);+ }+ const collection = await resolveCollection(args.items ?? [], args.coverImage);+ const work = await workModel.createAgentWork(run, {+ ...collection,+ description: args.description,+ title: args.title,+ type: 'collection',+ });+ return summarize(work, collection.items.length);+ }),+ delete: guarded(async (workId) => {+ const deleted = await workModel.deleteAgentWork(run, workId);+ return { title: deleted.title, workId: deleted.id };+ }),+ update: guarded(async (args) => {+ const collection = args.items+ ? await resolveCollection(args.items, args.coverImage)+ : undefined;+ const work = await workModel.updateAgentWork(run, {+ description: args.description,+ collection,+ title: args.title,+ workId: args.workId,+ });+ return summarize(work, collection?.items.length);+ }),+ };+};++/**+ * A run outside a conversation still gets the runtime: its calls return the+ * `unavailable` error instead of failing tool dispatch.+ */+const unavailableService = (error: WorkToolError): WorkToolService => {+ const refuse = async (): Promise<never> => {+ throw error;+ };+ return { create: refuse, delete: refuse, update: refuse };+};++export const workRuntime: ServerRuntimeRegistration = {+ identifier: WorkIdentifier,+ factory: (context) => {+ try {+ return new WorkExecutionRuntime(createWorkToolService(context));+ } catch (error) {+ if (error instanceof WorkToolError)+ return new WorkExecutionRuntime(unavailableService(error));+ throw error;+ }+ },+};diff --git a/apps/server/src/services/workRegistration/agentWork.test.ts b/apps/server/src/services/workRegistration/agentWork.test.tsnew file mode 100644index 00000000000..354de771122--- /dev/null+++ b/apps/server/src/services/workRegistration/agentWork.test.ts@@ -0,0 +1,375 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import type * as WorkModels from '@/database/models/work';+import type { LobeChatDatabase } from '@/database/type';+import type { HeteroOperationJwtClaims } from '@/libs/trpc/utils/internalJwt';+import { HeteroOperationPrincipalError } from '@/server/services/heterogeneousAgent/operationPrincipal';++import {+ AgentWorkRunError,+ parseCollectionImageRef,+ resolveAgentWorkCollectionItems,+ resolveAgentWorkFile,+ resolveAgentWorkRun,+} from './agentWork';++const mocks = vi.hoisted(() => ({+ fileAccessUrl: vi.fn(),+ findFile: vi.fn(),+ hasMembership: vi.fn(),+ principal: vi.fn(),+ shareVisitor: vi.fn(),+ workModelArgs: vi.fn(),+}));++vi.mock('@/database/models/workspace', () => ({+ hasActiveWorkspaceMembership: mocks.hasMembership,+}));+vi.mock('@/database/models/work', async (importOriginal) => ({+ AgentWorkError: (await importOriginal<typeof WorkModels>()).AgentWorkError,+ WorkModel: class {+ constructor(...args: unknown[]) {+ mocks.workModelArgs(...args);+ }+ },+}));+vi.mock('@/database/models/file', () => ({+ FileModel: class {+ findById = mocks.findFile;+ },+}));+vi.mock('@/server/services/file', () => ({+ FileService: class {+ getFileAccessUrl = mocks.fileAccessUrl;+ },+}));+vi.mock('@/server/services/heterogeneousAgent/operationPrincipal', async (importOriginal) => ({+ ...(await importOriginal<object>()),+ resolveActiveHeteroOperationPrincipal: mocks.principal,+}));+vi.mock('@/server/services/heterogeneousAgent/shareVisitor', () => ({+ resolveHeteroRunShareVisitor: mocks.shareVisitor,+}));++const claims = { operation_id: 'op_run', sub: 'user_1' } as HeteroOperationJwtClaims;+const operationAuth = { heteroAuthKind: 'operation', heteroOperation: claims };+const userAuth = { heteroAuthKind: 'user' };++const operationRow = (overrides: Record<string, unknown> = {}) => ({+ agentId: 'agt_1',+ status: 'running',+ threadId: null,+ topicId: 'tpc_1',+ userId: 'user_1',+ workspaceId: null,+ ...overrides,+});++const dbWith = (row: unknown) => {+ const query = {+ from: vi.fn(() => query),+ limit: vi.fn(async () => (row ? [row] : [])),+ where: vi.fn(() => query),+ };+ return { select: vi.fn(() => query) } as unknown as LobeChatDatabase;+};++const resolve = (row: unknown, auth: Record<string, unknown> = operationAuth) =>+ resolveAgentWorkRun({+ auth: auth as any,+ db: dbWith(row),+ operationId: 'op_run',+ userId: 'user_1',+ });++const expectStatus = async (promise: Promise<unknown>, status: number) => {+ const error = await promise.catch((caught: unknown) => caught);+ expect(error).toBeInstanceOf(AgentWorkRunError);+ expect((error as AgentWorkRunError).status).toBe(status);+};++describe('resolveAgentWorkRun', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mocks.principal.mockResolvedValue({ userId: 'user_1', workspaceId: undefined });+ mocks.shareVisitor.mockResolvedValue(undefined);+ mocks.hasMembership.mockResolvedValue(true);+ });++ it('resolves an operation token run to its topic under the ordinary scope', async () => {+ const { run, workspaceId } = await resolve(operationRow({ threadId: 'thd_1' }));++ expect(mocks.principal).toHaveBeenCalledWith(+ expect.objectContaining({ capability: 'work:write', claims, operationId: 'op_run' }),+ );+ expect(run).toEqual({+ agentId: 'agt_1',+ operationId: 'op_run',+ rootOperationId: 'op_run',+ threadId: 'thd_1',+ topicId: 'tpc_1',+ userId: 'user_1',+ });+ expect(workspaceId).toBeUndefined();+ expect(mocks.workModelArgs).toHaveBeenCalledWith(+ expect.anything(),+ 'user_1',+ undefined,+ undefined,+ );+ });++ it("stamps a sub-agent run's Works with the root operation the run completes under", async () => {+ const rows = [+ operationRow({ parentOperationId: 'op_parent' }),+ { id: 'op_parent', parentOperationId: 'op_root' },+ { id: 'op_root', parentOperationId: null },+ ];+ const query = {+ from: vi.fn(() => query),+ limit: vi.fn(async () => [rows.shift()]),+ where: vi.fn(() => query),+ };++ const { run } = await resolveAgentWorkRun({+ auth: operationAuth as any,+ db: { select: vi.fn(() => query) } as unknown as LobeChatDatabase,+ operationId: 'op_run',+ userId: 'user_1',+ });++ // Authorization stays on the named operation; only the cost key moves up.+ expect(run.operationId).toBe('op_run');+ expect(run.rootOperationId).toBe('op_root');+ });++ it("fences a share visitor's run to the visitor topic", async () => {+ mocks.shareVisitor.mockResolvedValue({ shareId: 'shr_1', visitorUserId: 'visitor_1' });++ await resolve(operationRow());++ expect(mocks.workModelArgs).toHaveBeenCalledWith(expect.anything(), 'user_1', undefined, {+ shareId: 'shr_1',+ topicId: 'tpc_1',+ type: 'agentShare',+ visitorUserId: 'visitor_1',+ });+ });++ it('maps a refused operation token onto its status', async () => {+ mocks.principal.mockRejectedValue(+ new HeteroOperationPrincipalError('Operation token lacks work:write', 403),+ );+ await expectStatus(resolve(operationRow()), 403);+ });++ it('rejects a legacy operation token', async () => {+ await expectStatus(resolve(operationRow(), { heteroAuthKind: 'legacy-operation' }), 401);+ });++ it("does not reveal another user's operation", async () => {+ await expectStatus(resolve(operationRow({ userId: 'user_2' }), userAuth), 404);+ await expectStatus(resolve(undefined, userAuth), 404);+ });++ it('rejects an operation that has ended or has no conversation', async () => {+ await expectStatus(resolve(operationRow({ status: 'completed' })), 409);+ await expectStatus(resolve(operationRow({ topicId: null })), 409);+ });++ it('requires a user session to still be a member of the run workspace', async () => {+ mocks.hasMembership.mockResolvedValue(false);+ await expectStatus(resolve(operationRow({ workspaceId: 'ws_1' }), userAuth), 403);++ mocks.hasMembership.mockResolvedValue(true);+ const { workspaceId } = await resolve(operationRow({ workspaceId: 'ws_1' }), userAuth);+ expect(workspaceId).toBe('ws_1');+ });+});++describe('resolveAgentWorkFile', () => {+ beforeEach(() => vi.clearAllMocks());++ const runOutputFile = {+ fileType: 'application/pdf',+ id: 'file_1',+ size: 2048,+ source: 'tool-result',+ url: 'files/2026-11-19/hash.pdf',+ userId: 'user_1',+ };++ it('reads size, type and URL from the file row', async () => {+ mocks.findFile.mockResolvedValue(runOutputFile);+ mocks.fileAccessUrl.mockResolvedValue('https://app.example.com/f/file_1');++ await expect(+ resolveAgentWorkFile({ db: dbWith(undefined), fileId: 'file_1', userId: 'user_1' }),+ ).resolves.toEqual({+ fileId: 'file_1',+ fileSize: 2048,+ fileUrl: 'https://app.example.com/f/file_1',+ mimeType: 'application/pdf',+ });+ });++ it.each([+ ["a file the caller can't see", undefined],+ ["a teammate's file in the workspace", { ...runOutputFile, userId: 'user_2' }],+ ['a file not uploaded as run output', { ...runOutputFile, source: 'chat' }],+ ])('refuses %s', async (_, file) => {+ mocks.findFile.mockResolvedValue(file);+ await expectStatus(+ resolveAgentWorkFile({+ db: dbWith(undefined),+ fileId: 'file_1',+ userId: 'user_1',+ workspaceId: 'ws_1',+ }),+ 404,+ );+ });+});++describe('parseCollectionImageRef', () => {+ it('reads a bare file id and the /f/ link image generation returns', () => {+ expect(parseCollectionImageRef('file_LkKoI7OfyZ0c')).toBe('file_LkKoI7OfyZ0c');+ expect(parseCollectionImageRef('https://app.lobehub.com/f/file_LkKoI7OfyZ0c')).toBe(+ 'file_LkKoI7OfyZ0c',+ );+ // The relative link a chat message renders for a stored file.+ expect(parseCollectionImageRef('/f/file_LkKoI7OfyZ0c')).toBe('file_LkKoI7OfyZ0c');+ });++ it('refuses any other link', () => {+ expect(() => parseCollectionImageRef('https://cdn.example.com/cat.png')).toThrow(+ AgentWorkRunError,+ );+ expect(() => parseCollectionImageRef('/images/cat.png')).toThrow(AgentWorkRunError);+ });+});++describe('resolveAgentWorkCollectionItems', () => {+ beforeEach(() => vi.clearAllMocks());++ it('refuses an empty or oversized list before resolving any image', async () => {+ for (const count of [0, 51]) {+ const error = await resolveAgentWorkCollectionItems({+ db: dbWith(undefined),+ items: Array.from({ length: count }, (_, i) => ({ image: `file_${i}` })),+ userId: 'user_1',+ }).catch((caught: unknown) => caught);+ expect((error as { code?: string }).code).toBe('BAD_REQUEST');+ }+ expect(mocks.findFile).not.toHaveBeenCalled();+ });++ const generatedImage = {+ fileType: 'image/png',+ id: 'file_img',+ size: 4096,+ source: 'image_generation',+ url: 'generations/hash.png',+ userId: 'user_1',+ };++ it('stores the URL and type from the file row, keeping the order and captions', async () => {+ mocks.findFile.mockImplementation(async (id: string) => ({ ...generatedImage, id }));+ mocks.fileAccessUrl.mockImplementation(+ async (file: { id: string }) => `https://app.example.com/f/${file.id}`,+ );++ await expect(+ resolveAgentWorkCollectionItems({+ db: dbWith(undefined),+ items: [+ { caption: ' Apple ', image: 'https://app.lobehub.com/f/file_a' },+ { image: 'file_b' },+ ],+ userId: 'user_1',+ }),+ ).resolves.toEqual([+ {+ caption: 'Apple',+ fileId: 'file_a',+ mimeType: 'image/png',+ url: 'https://app.example.com/f/file_a',+ },+ { fileId: 'file_b', mimeType: 'image/png', url: 'https://app.example.com/f/file_b' },+ ]);+ });++ it.each([+ ['an image of another user', { ...generatedImage, userId: 'user_2' }, 404],+ ['a library upload', { ...generatedImage, source: null }, 404],+ ['a file that is not an image', { ...generatedImage, fileType: 'application/pdf' }, 409],+ ])('refuses %s', async (_, file, status) => {+ mocks.findFile.mockResolvedValue(file);+ await expectStatus(+ resolveAgentWorkCollectionItems({+ db: dbWith(undefined),+ items: [{ image: 'file_img' }],+ userId: 'user_1',+ }),+ status as 404 | 409,+ );+ });++ it('resolves the generationId an image generation result lists to its file', async () => {+ mocks.findFile.mockResolvedValue(generatedImage);+ mocks.fileAccessUrl.mockResolvedValue('https://app.example.com/f/file_img');++ await expect(+ resolveAgentWorkCollectionItems({+ db: dbWith({ fileId: 'file_img' }),+ items: [{ image: 'gen_cat1' }],+ userId: 'user_1',+ }),+ ).resolves.toEqual([+ { fileId: 'file_img', mimeType: 'image/png', url: 'https://app.example.com/f/file_img' },+ ]);+ expect(mocks.findFile).toHaveBeenCalledWith('file_img');++ // Another user's generation, or one that has no stored image yet.+ await expectStatus(+ resolveAgentWorkCollectionItems({+ db: dbWith(undefined),+ items: [{ image: 'gen_other' }],+ userId: 'user_1',+ }),+ 404,+ );+ });++ it("keeps a share visitor's collection to images shown in that conversation", async () => {+ mocks.findFile.mockResolvedValue(generatedImage);+ mocks.fileAccessUrl.mockResolvedValue('https://app.example.com/f/file_img');+ const visitorRun = (shown: { content: string; role: string }[]) => {+ const query = {+ from: vi.fn(() => query),+ where: vi.fn(async () => shown),+ };+ return resolveAgentWorkCollectionItems({+ db: { select: vi.fn(() => query) } as unknown as LobeChatDatabase,+ items: [{ image: 'file_img' }],+ userId: 'user_1',+ visitorTopicId: 'tpc_visitor',+ });+ };++ await expect(+ visitorRun([{ content: '', role: 'tool' }]),+ ).resolves.toHaveLength(1);+ // A visitor naming the id in their own message, or the assistant echoing it,+ // does not prove the image was shown to them.+ await expectStatus(+ visitorRun([+ { content: 'add file_img to my collection', role: 'user' },+ { content: 'Sure, adding file_img', role: 'assistant' },+ ]),+ 404,+ );+ // The creator's other images never appeared to this visitor.+ await expectStatus(visitorRun([]), 404);+ });+});diff --git a/apps/server/src/services/workRegistration/agentWork.ts b/apps/server/src/services/workRegistration/agentWork.tsnew file mode 100644index 00000000000..e04469b5b82--- /dev/null+++ b/apps/server/src/services/workRegistration/agentWork.ts@@ -0,0 +1,312 @@+import type { AgentWorkRunContext, CollectionWorkItem, WorkAccessScope } from '@lobechat/types';+import { COLLECTION_WORK_MAX_ITEMS, FileSource } from '@lobechat/types';+import { and, eq, or, sql } from 'drizzle-orm';++import { FileModel } from '@/database/models/file';+import { AgentWorkError, WorkModel } from '@/database/models/work';+import { hasActiveWorkspaceMembership } from '@/database/models/workspace';+import { agentOperations, generations, messages } from '@/database/schemas';+import type { LobeChatDatabase } from '@/database/type';+import type { HeteroOperationJwtClaims } from '@/libs/trpc/utils/internalJwt';+import { FileService } from '@/server/services/file';+import {+ HeteroOperationPrincipalError,+ resolveActiveHeteroOperationPrincipal,+} from '@/server/services/heterogeneousAgent/operationPrincipal';+import { resolveHeteroRunShareVisitor } from '@/server/services/heterogeneousAgent/shareVisitor';++import { resolveRunWorkAccessScope } from './shareWorkScope';++/** Why a run may not register Works; `status` follows HTTP semantics. */+export class AgentWorkRunError extends Error {+ constructor(+ message: string,+ readonly status: 401 | 403 | 404 | 409,+ ) {+ super(message);+ this.name = 'AgentWorkRunError';+ }+}++/** Deepest parent chain walked; operation trees are a few levels deep. */+const MAX_OPERATION_DEPTH = 10;++/**+ * The top of the operation tree a run belongs to. Run completion fills the+ * cost of agent-written versions by the root operation id, so a sub-agent's+ * `lh work` call must stamp the root, not its own operation. Authorization+ * stays bound to the operation the caller named.+ */+const resolveRootOperationId = async (+ db: LobeChatDatabase,+ start: { operationId: string; parentOperationId: string | null; userId: string },+): Promise<string> => {+ let rootId = start.operationId;+ let parentId = start.parentOperationId;+ for (let depth = 0; parentId && depth < MAX_OPERATION_DEPTH; depth += 1) {+ const [parent] = await db+ .select({ id: agentOperations.id, parentOperationId: agentOperations.parentOperationId })+ .from(agentOperations)+ .where(and(eq(agentOperations.id, parentId), eq(agentOperations.userId, start.userId)))+ .limit(1);+ if (!parent) break;+ rootId = parent.id;+ parentId = parent.parentOperationId;+ }+ return rootId;+};++export interface AgentWorkRun {+ run: AgentWorkRunContext;+ workModel: WorkModel;+ workspaceId?: string;+}++/**+ * Resolve the running operation an `lh work` call belongs to, and the Work+ * scope it writes under. The topic, agent and share scope always come from the+ * operation row, never from the CLI.+ *+ * Two callers are accepted:+ * - A run's operation token (device, gateway and sandbox heterogeneous runs),+ * which must carry `work:write` and name this operation.+ * - A user session naming one of its own operations: the cloud sandbox `lh`+ * shim of a LobeHub agent run, or a logged-in device.+ */+export const resolveAgentWorkRun = async (params: {+ auth: { heteroAuthKind: string; heteroOperation?: HeteroOperationJwtClaims | null };+ db: LobeChatDatabase;+ operationId: string;+ userId: string;+}): Promise<AgentWorkRun> => {+ const { auth, db, operationId } = params;++ let userId: string;+ if (auth.heteroAuthKind === 'operation') {+ if (!auth.heteroOperation) throw new AgentWorkRunError('Invalid operation token', 401);+ try {+ ({ userId } = await resolveActiveHeteroOperationPrincipal({+ capability: 'work:write',+ claims: auth.heteroOperation,+ db,+ operationId,+ }));+ } catch (error) {+ if (!(error instanceof HeteroOperationPrincipalError)) throw error;+ throw new AgentWorkRunError(error.message, error.status);+ }+ } else if (auth.heteroAuthKind === 'user') {+ userId = params.userId;+ } else {+ throw new AgentWorkRunError('This token cannot register Works', 401);+ }++ const [operation] = await db+ .select({+ agentId: agentOperations.agentId,+ parentOperationId: agentOperations.parentOperationId,+ status: agentOperations.status,+ threadId: agentOperations.threadId,+ topicId: agentOperations.topicId,+ userId: agentOperations.userId,+ workspaceId: agentOperations.workspaceId,+ })+ .from(agentOperations)+ .where(eq(agentOperations.id, operationId))+ .limit(1);++ if (!operation || operation.userId !== userId) {+ throw new AgentWorkRunError(`Operation ${operationId} not found`, 404);+ }+ if (operation.status !== 'running') {+ throw new AgentWorkRunError('Operation has already ended', 409);+ }+ if (!operation.topicId) {+ throw new AgentWorkRunError('Operation has no conversation to attach Works to', 409);+ }+ const workspaceId = operation.workspaceId ?? undefined;+ if (+ auth.heteroAuthKind === 'user' &&+ workspaceId &&+ !(await hasActiveWorkspaceMembership(db, { userId, workspaceId }))+ ) {+ throw new AgentWorkRunError('Workspace membership is no longer active', 403);+ }++ const shareVisitor = await resolveHeteroRunShareVisitor({+ db,+ operationId,+ topicId: operation.topicId,+ });+ const accessScope: WorkAccessScope | null | undefined = resolveRunWorkAccessScope({+ shareVisitor,+ topicId: operation.topicId,+ });+ // `resolveRunWorkAccessScope` returns null only for a share run without a+ // topic, which the check above already rules out.+ if (accessScope === null) throw new AgentWorkRunError('Share run has no topic', 409);++ return {+ run: {+ agentId: operation.agentId,+ operationId,+ rootOperationId: await resolveRootOperationId(db, {+ operationId,+ parentOperationId: operation.parentOperationId,+ userId,+ }),+ threadId: operation.threadId,+ topicId: operation.topicId,+ userId,+ },+ workModel: new WorkModel(db, userId, workspaceId, accessScope),+ workspaceId,+ };+};++/**+ * The version metadata of an uploaded file, read from its file row. The CLI+ * names only the file id: the size, type and URL a Work card opens come from+ * the server, never from the agent.+ *+ * Only a file the caller uploaded as run output (`lh work` uploads with the+ * `tool-result` source) qualifies: a workspace member can see teammates'+ * files, and registering one would claim it as this run's output.+ */+export const resolveAgentWorkFile = async (params: {+ db: LobeChatDatabase;+ fileId: string;+ userId: string;+ workspaceId?: string;+}): Promise<{ fileId: string; fileSize: number; fileUrl: string; mimeType: string }> => {+ const { db, fileId, userId, workspaceId } = params;+ const file = await new FileModel(db, userId, workspaceId).findById(fileId);+ if (!file || file.userId !== userId || file.source !== FileSource.ToolResult) {+ throw new AgentWorkRunError(`File ${fileId} not found`, 404);+ }++ return {+ fileId: file.id,+ fileSize: file.size,+ fileUrl: await new FileService(db, userId, workspaceId).getFileAccessUrl(file),+ mimeType: file.fileType,+ };+};++/** Sources of the images a collection may hold: generated images and run outputs. */+const COLLECTION_IMAGE_SOURCES = new Set<string>([+ FileSource.ImageGeneration,+ FileSource.ToolResult,+]);++/**+ * The id an agent names a collection image by: the `generationId` (`gen_…`) an+ * image generation result lists, a bare `file_…` id, or a `/f/<id>` file link.+ */+export const parseCollectionImageRef = (ref: string): string => {+ const value = ref.trim();+ const isAbsolute = /^https?:\/\//i.test(value);+ // A relative `/f/<id>` link is what a chat message renders for a stored file.+ if (!isAbsolute && !value.startsWith('/')) return value;+ try {+ const { pathname } = isAbsolute ? new URL(value) : new URL(value, 'https://relative.invalid');+ const match = /^\/f\/([^/]+)\/?$/.exec(pathname);+ if (match) return decodeURIComponent(match[1]);+ } catch {+ // Fall through to the error below.+ }+ throw new AgentWorkRunError(`${value} is not a LobeHub file link (/f/<file id>)`, 404);+};++const isGenerationId = (id: string) => id.startsWith('gen_');++/**+ * Resolve the images of a collection to stored image entries. Each must be an+ * image the run's user generated or uploaded as run output; the URL the card+ * shows comes from the file row, never from the agent.+ *+ * `visitorTopicId` is set for a share visitor's run, which executes as the+ * creator: each image must then appear in a tool result of that visitor's+ * conversation, so a visitor cannot pull the creator's other images into a+ * card by guessing their ids.+ */+export const resolveAgentWorkCollectionItems = async (params: {+ db: LobeChatDatabase;+ items: { caption?: string; image: string }[];+ userId: string;+ visitorTopicId?: string;+ workspaceId?: string;+}): Promise<CollectionWorkItem[]> => {+ const { db, items, userId, visitorTopicId, workspaceId } = params;+ // Check the count before resolving: every item costs file (and generation)+ // queries, so an oversized list is refused before any of them run.+ if (items.length === 0) {+ throw new AgentWorkError('BAD_REQUEST', 'A collection needs at least one image');+ }+ if (items.length > COLLECTION_WORK_MAX_ITEMS) {+ throw new AgentWorkError(+ 'BAD_REQUEST',+ `A collection holds at most ${COLLECTION_WORK_MAX_ITEMS} images`,+ );+ }+ const fileModel = new FileModel(db, userId, workspaceId);+ const fileService = new FileService(db, userId, workspaceId);++ const files = await Promise.all(+ items.map(async ({ caption, image }) => {+ const ref = parseCollectionImageRef(image);+ let fileId = ref;+ if (isGenerationId(ref)) {+ // Image generation results name the generation; its stored image is the file.+ const [generation] = await db+ .select({ fileId: generations.fileId })+ .from(generations)+ .where(and(eq(generations.id, ref), eq(generations.userId, userId)))+ .limit(1);+ if (!generation?.fileId) throw new AgentWorkRunError(`Image ${image} not found`, 404);+ fileId = generation.fileId;+ }+ const file = await fileModel.findById(fileId);+ if (!file || file.userId !== userId || !COLLECTION_IMAGE_SOURCES.has(file.source ?? '')) {+ throw new AgentWorkRunError(`Image ${image} not found`, 404);+ }+ if (!file.fileType.startsWith('image/')) {+ throw new AgentWorkRunError(`File ${fileId} is not an image`, 409);+ }+ return { caption, file, image, ref };+ }),+ );++ if (visitorTopicId) {+ // Generated images live in generation topics; the conversation only holds+ // the id the agent names them by (the generation id or file link) in the+ // tool result that produced them. One scan of the topic returns the+ // messages naming any of the images.+ const shown = await db+ .select({ content: messages.content, role: messages.role })+ .from(messages)+ .where(+ and(+ eq(messages.topicId, visitorTopicId),+ eq(messages.userId, userId),+ or(...files.map(({ ref }) => sql`position(${ref} in ${messages.content}) > 0`)),+ ),+ );+ // Only tool results count: a message the visitor typed, or an assistant+ // reply echoing it, can name any id the visitor guessed.+ const toolResults = shown.filter(({ role }) => role === 'tool');+ const missing = files.find(+ ({ ref }) => !toolResults.some(({ content }) => content?.includes(ref)),+ );+ if (missing) throw new AgentWorkRunError(`Image ${missing.image} not found`, 404);+ }++ return Promise.all(+ files.map(async ({ caption, file }) => ({+ ...(caption?.trim() ? { caption: caption.trim() } : {}),+ fileId: file.id,+ mimeType: file.fileType,+ url: await fileService.getFileAccessUrl(file),+ })),+ );+};diff --git a/apps/server/src/services/workRegistration/index.ts b/apps/server/src/services/workRegistration/index.tsindex 7218520a780..e730c3df11d 100644--- a/apps/server/src/services/workRegistration/index.ts+++ b/apps/server/src/services/workRegistration/index.ts@@ -13,10 +13,21 @@* runtime state, used to suppress the early `visible_output_end` when* completion will export files.*+ * - `resolveAgentWorkRun` / `resolveAgentWorkFile` — resolve the running+ * operation and uploaded file behind an agent's own `lh work create|update`.+ ** Execution-time registrations (skill structured tools, task / document* works) live with their owning features — see `WorkModel` and the agent-work* skill's file map.*/+export {+ type AgentWorkRun,+ AgentWorkRunError,+ parseCollectionImageRef,+ resolveAgentWorkCollectionItems,+ resolveAgentWorkFile,+ resolveAgentWorkRun,+} from './agentWork';export {type LocalRunShellWorksResult,registerShellWorksForLocalRun,diff --git a/apps/server/src/services/workRegistration/registerWorksForOperation.test.ts b/apps/server/src/services/workRegistration/registerWorksForOperation.test.tsindex d35b483e02b..b7223da4aed 100644--- a/apps/server/src/services/workRegistration/registerWorksForOperation.test.ts+++ b/apps/server/src/services/workRegistration/registerWorksForOperation.test.ts@@ -15,11 +15,13 @@ const {mockFindFileVersionByToolCall,mockExportAndUploadFile,mockCreateSandboxService,+ mockFillAgentWorkCost,mockUpdateMessage,mockFindMessageById,} = vi.hoisted(() => ({mockCreateSandboxService: vi.fn(),mockExportAndUploadFile: vi.fn(),+ mockFillAgentWorkCost: vi.fn(),mockFindById: vi.fn(),mockFindFileVersionByToolCall: vi.fn(),mockFindMessageById: vi.fn(),@@ -53,6 +55,7 @@ vi.mock('@/database/models/message', () => ({vi.mock('@/database/models/work', () => ({WorkModel: vi.fn(function () {return {+ fillAgentWorkCost: mockFillAgentWorkCost,findFileVersionByToolCall: mockFindFileVersionByToolCall,registerFile: mockRegisterFile,registerShellArtboardResult: mockRegisterShellArtboardResult,@@ -184,6 +187,16 @@ beforeEach(() => {});describe('registerWorksForOperation', () => {+ it('fills the cost of agent-written Works even when the run left no plugin records', async () => {+ mockListPlugins.mockResolvedValue([]);++ await registerWorksForOperation(baseParams);++ expect(mockFillAgentWorkCost).toHaveBeenCalledWith(+ expect.objectContaining({ cumulativeCost: 0.5, rootOperationId: 'op-1' }),+ );+ });+it('registers a share visitor run under the share scope with file provenance', async () => {mockListPlugins.mockResolvedValue([writeRow('a', '/mnt/data/deck.pptx')]);const agentShareVisitor = { shareId: 'share-1', visitorUserId: 'visitor-1' };diff --git a/apps/server/src/services/workRegistration/registerWorksForOperation.ts b/apps/server/src/services/workRegistration/registerWorksForOperation.tsindex b6ff2974d1f..a9262e76564 100644--- a/apps/server/src/services/workRegistration/registerWorksForOperation.ts+++ b/apps/server/src/services/workRegistration/registerWorksForOperation.ts@@ -360,6 +360,45 @@ export const registerWorksForOperation = async (return { attempted: 0, failed: 0 };}+ const workModel = new WorkModel(serverDB, userId, workspaceId, accessScope);++ // The whole operation's spend/usage is attached to each version registered+ // this round (an operation-level, not per-file, figure — the scanner can't+ // attribute cost to individual files). Prefer the terminal state's live blobs+ // over the op row: on the pre-snapshot path the row's cost/usage columns are+ // written only later by `recordCompletion`, so the row reads null/stale here.+ // The op row's `totalCost` also rolls up terminal child ops; replicate that+ // from the already-loaded tree (children complete before their root, so their+ // rows carry final totals) to keep the state-sourced figure equivalent.+ const childCost = tree+ .filter((op) => op.id !== operationId)+ .reduce((sum, op) => sum + (op.totalCost ?? 0), 0);+ const ownCost = params.finalCost?.total;+ const cumulativeCost =+ typeof ownCost === 'number' ? ownCost + childCost : (completingOp.totalCost ?? null);+ const usageBlob = params.finalUsage ?? completingOp.usage;+ const cumulativeUsage: WorkVersionCumulativeUsage | null = usageBlob+ ? {+ capturedAt: new Date().toISOString(),+ cost: params.finalCost ?? completingOp.cost ?? undefined,+ usage: usageBlob,+ }+ : null;++ // Works the agent wrote itself (`lobe-work` / `lh work`) were saved mid-run+ // without a cost; give them the same run total the Works below carry. This+ // runs before the record scan: a run whose only output is such a Work may+ // leave no plugin records the scan below needs.+ try {+ await workModel.fillAgentWorkCost({+ cumulativeCost,+ cumulativeUsage,+ rootOperationId: operationId,+ });+ } catch (error) {+ log('[%s] Failed to fill agent Work cost (non-fatal): %O', operationId, error);+ }+// A share visitor's tool rows live under a topic with a non-null `senderId`,// which `MessageModel.ownership()` excludes by default — without the opt-in// the scan (and the anchor stamp below) silently sees nothing for that run.@@ -398,31 +437,6 @@ export const registerWorksForOperation = async (return undefined;};- const workModel = new WorkModel(serverDB, userId, workspaceId, accessScope);-- // The whole operation's spend/usage is attached to each version registered- // this round (an operation-level, not per-file, figure — the scanner can't- // attribute cost to individual files). Prefer the terminal state's live blobs- // over the op row: on the pre-snapshot path the row's cost/usage columns are- // written only later by `recordCompletion`, so the row reads null/stale here.- // The op row's `totalCost` also rolls up terminal child ops; replicate that- // from the already-loaded tree (children complete before their root, so their- // rows carry final totals) to keep the state-sourced figure equivalent.- const childCost = tree- .filter((op) => op.id !== operationId)- .reduce((sum, op) => sum + (op.totalCost ?? 0), 0);- const ownCost = params.finalCost?.total;- const cumulativeCost =- typeof ownCost === 'number' ? ownCost + childCost : (completingOp.totalCost ?? null);- const usageBlob = params.finalUsage ?? completingOp.usage;- const cumulativeUsage: WorkVersionCumulativeUsage | null = usageBlob- ? {- capturedAt: new Date().toISOString(),- cost: params.finalCost ?? completingOp.cost ?? undefined,- usage: usageBlob,- }- : null;-// Recover external Works (github issue/PR today) from hetero / device shell// records (codex, claude-code, lobe-local-system) — these surfaces never pass// the skill-tool registration hook. Self-guarded: per-record failures arediff --git a/locales/en-US/agent.json b/locales/en-US/agent.jsonindex 7debe48e0de..df7e7899a1f 100644--- a/locales/en-US/agent.json+++ b/locales/en-US/agent.json@@ -927,15 +927,19 @@"share.visitor.profile.terms.visibilityCreator": "The creator has turned on topic access and may read the messages in your topics.","share.visitor.profile.terms.visibilityPrivate": "Only you can see your topics.","share.visitor.profile.works.desc": "Selected by the creator. See what this agent can deliver.",+ "share.visitor.profile.works.images_one": "{{count}} image",+ "share.visitor.profile.works.images_other": "{{count}} images","share.visitor.profile.works.open": "Open work","share.visitor.profile.works.title": "Featured works","share.visitor.profile.works.type.artboard": "Artboard","share.visitor.profile.works.type.canvas": "Canvas",+ "share.visitor.profile.works.type.collection": "Gallery","share.visitor.profile.works.type.document": "Document","share.visitor.profile.works.type.external": "Linked work","share.visitor.profile.works.type.file": "File","share.visitor.profile.works.type.task": "Task","share.visitor.profile.works.untitled": "Untitled work",+ "share.visitor.profile.works.viewImages": "View images","share.visitor.topBar.home": "Go to my LobeHub","share.visitor.upload.creatorStorageBlocked": "This Agent's upload space is full. Ask its creator to free up room or raise the cap.","share.visitor.upload.fileTooLarge": "Files must be under {{max}}.",diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex 0e460e6b988..cf416844c20 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -4095,6 +4095,10 @@"workingPanel.works.canvasUntitled": "Untitled canvas","workingPanel.works.changeType.created": "Created","workingPanel.works.changeType.updated": "Updated",+ "workingPanel.works.collectionCount_one": "{{count}} image",+ "workingPanel.works.collectionCount_other": "{{count}} images",+ "workingPanel.works.collectionEmpty": "This gallery has no images",+ "workingPanel.works.collectionUntitled": "Untitled gallery","workingPanel.works.documentDeleted": "This document has been deleted","workingPanel.works.documentLoadError": "Failed to load document","workingPanel.works.empty": "No works in this conversation yet",diff --git a/locales/en-US/file.json b/locales/en-US/file.jsonindex de5cfffd942..7f91710c6d8 100644--- a/locales/en-US/file.json+++ b/locales/en-US/file.json@@ -554,12 +554,14 @@"work.totalCost": "Total cost {{cost}}","work.type.artboard": "Artboard","work.type.canvas": "Canvas",+ "work.type.collection": "Gallery","work.type.document": "Document","work.type.file": "File","work.type.githubIssue": "GitHub Issue","work.type.githubPullRequest": "GitHub PR","work.type.linearDocument": "Linear Document","work.type.linearIssue": "Linear Issue",+ "work.type.link": "Link","work.type.task": "Task","work.updatedAt": "Updated {{date}}"}diff --git a/locales/en-US/plugin.json b/locales/en-US/plugin.jsonindex a02459c6519..af022ab21ae 100644--- a/locales/en-US/plugin.json+++ b/locales/en-US/plugin.json@@ -833,6 +833,13 @@"builtins.lobe-webhook.render.testRefused": "The test call wasn't accepted (HTTP {{status}}).","builtins.lobe-webhook.render.testSent": "Test call accepted. The agent is running it; see it under the webhook calls.","builtins.lobe-webhook.title": "Webhooks",+ "builtins.lobe-work.apiName.createWork": "Create Work",+ "builtins.lobe-work.apiName.deleteWork": "Delete Work",+ "builtins.lobe-work.apiName.updateWork": "Update Work",+ "builtins.lobe-work.inspector.failed": "Failed",+ "builtins.lobe-work.inspector.images_one": "{{count}} image",+ "builtins.lobe-work.inspector.images_other": "{{count}} images",+ "builtins.lobe-work.title": "Works","builtins.shellCommand.acceptance.feedback": "Read acceptance feedback","builtins.shellCommand.acceptance.ingest": "Publish acceptance round","builtins.shellCommand.acceptance.linkPr": "Link PR to acceptance",diff --git a/locales/zh-CN/agent.json b/locales/zh-CN/agent.jsonindex 63cbe567157..30a2c1be331 100644--- a/locales/zh-CN/agent.json+++ b/locales/zh-CN/agent.json@@ -927,15 +927,19 @@"share.visitor.profile.terms.visibilityCreator": "创建者开启了话题查看权限,可能会读取你话题中的消息。","share.visitor.profile.terms.visibilityPrivate": "你的话题只有你自己能看到。","share.visitor.profile.works.desc": "由创建者精选,看看这个助手能交付什么。",+ "share.visitor.profile.works.images_one": "{{count}} 张图片",+ "share.visitor.profile.works.images_other": "{{count}} 张图片","share.visitor.profile.works.open": "打开成果","share.visitor.profile.works.title": "精选成果","share.visitor.profile.works.type.artboard": "画板","share.visitor.profile.works.type.canvas": "画布",+ "share.visitor.profile.works.type.collection": "图集","share.visitor.profile.works.type.document": "文档","share.visitor.profile.works.type.external": "外部成果","share.visitor.profile.works.type.file": "文件","share.visitor.profile.works.type.task": "任务","share.visitor.profile.works.untitled": "未命名成果",+ "share.visitor.profile.works.viewImages": "查看图片","share.visitor.topBar.home": "回到我的 LobeHub","share.visitor.upload.creatorStorageBlocked": "这个智能体的上传空间已满,请联系创建者清理文件或调高上限。","share.visitor.upload.fileTooLarge": "单个文件不能超过 {{max}}。",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex b1a92adfd27..8b2437c972b 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -4095,6 +4095,10 @@"workingPanel.works.canvasUntitled": "未命名画布","workingPanel.works.changeType.created": "已创建","workingPanel.works.changeType.updated": "已编辑",+ "workingPanel.works.collectionCount_one": "{{count}} 张图片",+ "workingPanel.works.collectionCount_other": "{{count}} 张图片",+ "workingPanel.works.collectionEmpty": "这个图集还没有图片",+ "workingPanel.works.collectionUntitled": "未命名图集","workingPanel.works.documentDeleted": "文档已被删除","workingPanel.works.documentLoadError": "文档加载失败","workingPanel.works.empty": "当前会话暂无产物",diff --git a/locales/zh-CN/file.json b/locales/zh-CN/file.jsonindex f385b861089..8ac18c705bb 100644--- a/locales/zh-CN/file.json+++ b/locales/zh-CN/file.json@@ -554,12 +554,14 @@"work.totalCost": "累计开销 {{cost}}","work.type.artboard": "画板","work.type.canvas": "画布",+ "work.type.collection": "图集","work.type.document": "文档","work.type.file": "文件","work.type.githubIssue": "GitHub Issue","work.type.githubPullRequest": "GitHub PR","work.type.linearDocument": "Linear 文档","work.type.linearIssue": "Linear Issue",+ "work.type.link": "链接","work.type.task": "任务","work.updatedAt": "更新于 {{date}}"}diff --git a/locales/zh-CN/plugin.json b/locales/zh-CN/plugin.jsonindex e3fff6839d4..d0a7de9b08c 100644--- a/locales/zh-CN/plugin.json+++ b/locales/zh-CN/plugin.json@@ -833,6 +833,13 @@"builtins.lobe-webhook.render.testRefused": "测试调用未被接收(HTTP {{status}})。","builtins.lobe-webhook.render.testSent": "测试调用已接收,助理正在运行,可在调用记录中查看。","builtins.lobe-webhook.title": "Webhook",+ "builtins.lobe-work.apiName.createWork": "创建成果",+ "builtins.lobe-work.apiName.deleteWork": "删除成果",+ "builtins.lobe-work.apiName.updateWork": "更新成果",+ "builtins.lobe-work.inspector.failed": "失败",+ "builtins.lobe-work.inspector.images_one": "{{count}} 张图片",+ "builtins.lobe-work.inspector.images_other": "{{count}} 张图片",+ "builtins.lobe-work.title": "成果","builtins.shellCommand.acceptance.feedback": "查看验收反馈","builtins.shellCommand.acceptance.ingest": "发布验收轮次","builtins.shellCommand.acceptance.linkPr": "关联 PR 到验收",diff --git a/package.json b/package.jsonindex a6d0375d7fc..e259a99e47a 100644--- a/package.json+++ b/package.json@@ -289,6 +289,7 @@"@lobechat/builtin-tool-web-browsing": "workspace:*","@lobechat/builtin-tool-web-onboarding": "workspace:*","@lobechat/builtin-tool-webhook": "workspace:*",+ "@lobechat/builtin-tool-work": "workspace:*","@lobechat/builtin-tools": "workspace:*","@lobechat/business-config": "workspace:*","@lobechat/business-const": "workspace:*",diff --git a/packages/builtin-skills/src/lobehub/content.ts b/packages/builtin-skills/src/lobehub/content.tsindex c171fe18c08..ebf757f7ff7 100644--- a/packages/builtin-skills/src/lobehub/content.ts+++ b/packages/builtin-skills/src/lobehub/content.ts@@ -55,6 +55,7 @@ run commands.| \`lh kb\` | Knowledge base management (create, upload, organize) | \`references/kb\` || \`lh file\` | File management | \`references/file\` || \`lh artifact\` | Publish local HTML or Canvas, with persistent bindings and retry recovery | \`references/artifact\` |+| \`lh work\` | Show files and links you produced as Work cards under your reply (create, update) | \`references/work\` || \`lh memory\` | User memory management (identity, activity, preference) | \`references/memory\` || \`lh search\` / \`lh recall\` | Search local resources or the web / recall past work in a time window | \`references/search\` || \`lh gen\` | Content generation (text, image, video, TTS, ASR) | \`references/generate\` |diff --git a/packages/builtin-skills/src/lobehub/index.ts b/packages/builtin-skills/src/lobehub/index.tsindex b399fa76719..dbc603cec53 100644--- a/packages/builtin-skills/src/lobehub/index.ts+++ b/packages/builtin-skills/src/lobehub/index.ts@@ -37,6 +37,7 @@ import task from './references/task.md';import topic from './references/topic';import trace from './references/trace';import webhook from './references/webhook';+import work from './references/work';import workspace from './references/workspace';export { LobeHubIdentifier };@@ -79,6 +80,7 @@ export const LobeHubSkill: BuiltinSkill = {'references/topic': topic,'references/trace': trace,'references/webhook': webhook,+ 'references/work': work,'references/workspace': workspace,}),};diff --git a/packages/builtin-skills/src/lobehub/references/work.ts b/packages/builtin-skills/src/lobehub/references/work.tsnew file mode 100644index 00000000000..eacd6a8145a--- /dev/null+++ b/packages/builtin-skills/src/lobehub/references/work.ts@@ -0,0 +1,40 @@+const content = `# lh work - Register What You Produced++A Work is a card under your reply that links to something you made: a file or a+web page. Users find their Works on the reply and in the resource library.++## Subcommands++- \`lh work create --file <path> [--title <title>] [--description <text>] [--json]\` - Upload a+ file you produced and show it as a Work card. The title defaults to the file name.+- \`lh work create --url <url> --title <title> [--description <text>] [--json]\` - Register an+ http(s) link you produced, such as a deployed site or a published post.+- \`lh work update <work-id> [--file <path>] [--title <title>] [--description <text>] [--json]\` -+ Add a new version to a Work you created. Options left out keep their values. A link+ keeps its URL: register a new link with \`lh work create --url <url> --title <title>\` instead.+- \`lh work delete <work-id> [--json]\` - Delete a Work you created by mistake. Its card and+ versions go; uploaded files stay. A Work a goal, delivery or project already holds cannot+ be deleted: update it instead.+- \`lh work lookup <github-pr-url>\` - Find the conversations linked to a GitHub pull request.++## When to use it++- Register a deliverable the user should open later: a report, a slide deck, a+ generated image, a deployed preview. Skip scratch files and intermediate output.+- Run these inside your agent run; they attach the Work to the current reply+ (\`LOBEHUB_OPERATION_ID\`, or \`--operation <id>\`).+- Creating the same file path or link again in this conversation adds a version to the+ same Work, so you can also re-run \`create\` after changing a file.+- Keep the \`id\` from \`--json\` to update the Work later.++## What not to register++- GitHub pull requests and issues, and Linear issues: they become Works automatically+ when you create or edit them, and \`lh work create\` refuses their links.+- Works registered automatically cannot be changed with \`lh work update\` or deleted with+ \`lh work delete\`.+- Several images in one card: use the \`lobe-work\` tool's \`createWork\` with \`type: collection\`+ instead of one file Work per image.+`;++export default content;diff --git a/packages/builtin-tool-work/package.json b/packages/builtin-tool-work/package.jsonnew file mode 100644index 00000000000..e276be85560--- /dev/null+++ b/packages/builtin-tool-work/package.json@@ -0,0 +1,20 @@+{+ "name": "@lobechat/builtin-tool-work",+ "version": "1.0.0",+ "private": true,+ "type": "module",+ "exports": {+ ".": "./src/index.ts",+ "./client": "./src/client/index.ts",+ "./executionRuntime": "./src/ExecutionRuntime/index.ts"+ },+ "main": "./src/index.ts",+ "devDependencies": {+ "@lobechat/types": "workspace:*"+ },+ "peerDependencies": {+ "@lobehub/ui": "^6.0.4",+ "react": "*",+ "react-i18next": "*"+ }+}diff --git a/packages/builtin-tool-work/src/ExecutionRuntime/index.test.ts b/packages/builtin-tool-work/src/ExecutionRuntime/index.test.tsnew file mode 100644index 00000000000..1a397017aa7--- /dev/null+++ b/packages/builtin-tool-work/src/ExecutionRuntime/index.test.ts@@ -0,0 +1,128 @@+import { describe, expect, it, vi } from 'vitest';++import { WorkExecutionRuntime, WorkToolError, type WorkToolService } from './index';++const service = (overrides: Partial<WorkToolService> = {}): WorkToolService => ({+ create: vi.fn(async (args) => ({+ imageCount: args.items?.length,+ title: args.title,+ type: args.type,+ workId: 'wk_1',+ })),+ delete: vi.fn(async (workId) => ({ title: 'Covers', workId })),+ update: vi.fn(async (args) => ({+ imageCount: args.items?.length,+ title: args.title ?? 'Covers',+ type: 'collection' as const,+ workId: args.workId,+ })),+ ...overrides,+});++const images = [{ image: 'file_a' }, { caption: 'Night', image: 'file_b' }];++describe('WorkExecutionRuntime', () => {+ it('creates a collection and names its id, title and image count', async () => {+ const runtime = new WorkExecutionRuntime(service());+ const result = await runtime.createWork({ items: images, title: 'Covers', type: 'collection' });++ expect(result.success).toBe(true);+ expect(result.content).toContain('wk_1');+ expect(result.content).toContain('"Covers"');+ expect(result.content).toContain('2 images');+ expect(result.state).toEqual({+ work: { imageCount: 2, title: 'Covers', type: 'collection', workId: 'wk_1' },+ });+ });++ it('refuses a collection without images and a link without a url, before writing', async () => {+ const svc = service();+ const runtime = new WorkExecutionRuntime(svc);++ const collection = await runtime.createWork({ title: 'Covers', type: 'collection' });+ const link = await runtime.createWork({ title: 'Site', type: 'link' });++ expect(collection.error?.type).toBe('invalid_input');+ expect(link.error?.type).toBe('invalid_input');+ expect(svc.create).not.toHaveBeenCalled();+ });++ it('refuses an update that changes nothing or empties the collection', async () => {+ const svc = service();+ const runtime = new WorkExecutionRuntime(svc);++ expect((await runtime.updateWork({ workId: 'wk_1' })).error?.type).toBe('invalid_input');+ expect((await runtime.updateWork({ items: [], workId: 'wk_1' })).error?.type).toBe(+ 'invalid_input',+ );+ expect((await runtime.updateWork({ coverImage: 'file_a', workId: 'wk_1' })).error?.type).toBe(+ 'invalid_input',+ );+ expect(svc.update).not.toHaveBeenCalled();+ });++ it('passes the full items list through on update', async () => {+ const svc = service();+ const result = await new WorkExecutionRuntime(svc).updateWork({+ items: images,+ workId: 'wk_1',+ });++ expect(svc.update).toHaveBeenCalledWith({ items: images, workId: 'wk_1' });+ expect(result.content).toContain('2 images');+ });++ it('counts a single image in the singular', async () => {+ const result = await new WorkExecutionRuntime(service()).createWork({+ items: [{ image: 'file_a' }],+ title: 'Cover',+ type: 'collection',+ });++ expect(result.content).toContain(', 1 image)');+ });++ it('deletes a Work and says the images stay', async () => {+ const result = await new WorkExecutionRuntime(service()).deleteWork({ workId: 'wk_1' });++ expect(result.success).toBe(true);+ expect(result.content).toContain('wk_1');+ expect(result.state).toEqual({ deleted: { title: 'Covers', workId: 'wk_1' } });+ });++ it('keeps a known error code and turns anything else into unknown', async () => {+ const known = new WorkExecutionRuntime(+ service({+ delete: async () => {+ throw new WorkToolError('not_found', 'Work wk_x not found');+ },+ }),+ );+ const unknown = new WorkExecutionRuntime(+ service({+ delete: async () => {+ throw new Error('Failed query: delete from "works" where "id" = $1 params: wk_x');+ },+ }),+ );+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});++ const notFound = await known.deleteWork({ workId: 'wk_x' });+ expect(notFound).toMatchObject({+ content: 'Work wk_x not found',+ error: { message: 'Work wk_x not found', type: 'not_found' },+ state: { error: { code: 'not_found', message: 'Work wk_x not found' } },+ success: false,+ });+ // A database error never reaches the model or the stored tool state.+ const failed = await unknown.deleteWork({ workId: 'wk_x' });+ expect(failed).toMatchObject({+ content: 'Failed to delete the Work. Try again later.',+ error: { type: 'unknown' },+ state: { error: { code: 'unknown' } },+ });+ expect(JSON.stringify(failed)).not.toContain('Failed query');+ expect(consoleError).toHaveBeenCalled();+ consoleError.mockRestore();+ });+});diff --git a/packages/builtin-tool-work/src/ExecutionRuntime/index.ts b/packages/builtin-tool-work/src/ExecutionRuntime/index.tsnew file mode 100644index 00000000000..d35a0d48f6e--- /dev/null+++ b/packages/builtin-tool-work/src/ExecutionRuntime/index.ts@@ -0,0 +1,112 @@+import type { BuiltinServerRuntimeOutput } from '@lobechat/types';++import type {+ CreateWorkArgs,+ DeleteWorkArgs,+ DeleteWorkState,+ UpdateWorkArgs,+ WorkState,+ WorkSummary,+ WorkToolErrorCode,+ WorkToolErrorState,+} from '../types';+import { WORK_TOOL_ERROR_CODES } from '../types';++/**+ * The server's Work writes for the running agent. The run (conversation,+ * operation, share scope) is bound by the server when it builds this service;+ * nothing here takes it from the model.+ */+export interface WorkToolService {+ create: (args: CreateWorkArgs) => Promise<WorkSummary>;+ delete: (workId: string) => Promise<{ title: string | null; workId: string }>;+ update: (args: UpdateWorkArgs) => Promise<WorkSummary>;+}++/** A refused call with a stable code the inspector and the model can read. */+export class WorkToolError extends Error {+ constructor(+ readonly code: WorkToolErrorCode,+ message: string,+ ) {+ super(message);+ this.name = 'WorkToolError';+ }+}++const ERROR_CODES = new Set<WorkToolErrorCode>(WORK_TOOL_ERROR_CODES);++const describeWork = (verb: string, work: WorkSummary) => {+ const count = work.imageCount;+ const images = typeof count === 'number' ? `, ${count} ${count === 1 ? 'image' : 'images'}` : '';+ return `${verb} ${work.type} Work ${work.workId} ("${work.title ?? ''}"${images}). Use workId ${work.workId} to update or delete it.`;+};++const invalid = (message: string) => new WorkToolError('invalid_input', message);++export class WorkExecutionRuntime {+ constructor(private readonly service: WorkToolService) {}++ private async result<T>(+ action: 'create' | 'delete' | 'update',+ run: () => Promise<{ content: string; state: T }>,+ ): Promise<BuiltinServerRuntimeOutput> {+ try {+ const { content, state } = await run();+ return { content, state, success: true };+ } catch (error) {+ // Only a refusal raised as `WorkToolError` is worded for the model. Any+ // other error (a database failure, for one) may carry SQL and parameters,+ // so the model and the stored tool state get a generic message instead.+ const known = error instanceof WorkToolError && ERROR_CODES.has(error.code);+ if (!known) console.error(`[lobe-work] Failed to ${action} the Work:`, error);+ const code: WorkToolErrorCode = known ? error.code : 'unknown';+ const message =+ known && error.message ? error.message : `Failed to ${action} the Work. Try again later.`;+ const state: WorkToolErrorState = { error: { code, message } };+ return { content: message, error: { message, type: code }, state, success: false };+ }+ }++ createWork = (args: CreateWorkArgs) =>+ this.result<WorkState>('create', async () => {+ if (!args?.title?.trim()) throw invalid('A Work needs a title.');+ if (args.type === 'collection') {+ if (!args.items?.length) throw invalid('A collection needs at least one image in items.');+ if (args.url) throw invalid('A collection takes images in items, not a url.');+ } else if (args.type === 'link') {+ if (!args.url) throw invalid('A link Work needs a url.');+ if (args.items?.length || args.coverImage) throw invalid('A link Work takes no images.');+ } else {+ throw invalid('type must be "collection" or "link".');+ }+ const work = await this.service.create(args);+ return { content: describeWork('Created', work), state: { work } };+ });++ updateWork = (args: UpdateWorkArgs) =>+ this.result<WorkState>('update', async () => {+ if (!args?.workId) throw invalid('workId is required.');+ if (args.items && args.items.length === 0) {+ throw invalid('items must list at least one image; delete the Work instead.');+ }+ if (args.coverImage && !args.items) {+ throw invalid('Pass the full items list together with coverImage.');+ }+ if (args.title === undefined && args.description === undefined && !args.items) {+ throw invalid('Nothing to update: pass title, description or items.');+ }+ const work = await this.service.update(args);+ return { content: describeWork('Updated', work), state: { work } };+ });++ deleteWork = (args: DeleteWorkArgs) =>+ this.result<DeleteWorkState>('delete', async () => {+ if (!args?.workId) throw invalid('workId is required.');+ const deleted = await this.service.delete(args.workId);+ return {+ content: `Deleted Work ${deleted.workId}${deleted.title ? ` ("${deleted.title}")` : ''}. Its images stay in the file store.`,+ state: { deleted },+ };+ });+}diff --git a/packages/builtin-tool-work/src/client/Inspector/index.tsx b/packages/builtin-tool-work/src/client/Inspector/index.tsxnew file mode 100644index 00000000000..a9eb25d19e2--- /dev/null+++ b/packages/builtin-tool-work/src/client/Inspector/index.tsx@@ -0,0 +1,70 @@+'use client';++import type { BuiltinInspector, BuiltinInspectorProps } from '@lobechat/types';+import { cssVar, cx, Text } from '@lobehub/ui';+import { useTranslation } from 'react-i18next';++import { highlightTextStyles, inspectorTextStyles, shinyTextStyles } from '@/styles';++import {+ type CreateWorkArgs,+ type DeleteWorkState,+ WorkApiName,+ type WorkState,+ type WorkToolErrorState,+} from '../../types';++type InspectorState = Partial<DeleteWorkState & WorkState & WorkToolErrorState>;++/**+ * The header line of every Work call: the action, the Work's title once known+ * (from the arguments while they stream, from the result afterwards), then the+ * collection's image count or a failure mark. One component for all APIs.+ */+const WorkInspector = ({+ apiName,+ args,+ isArgumentsStreaming,+ isLoading,+ partialArgs,+ pluginState,+ result,+}: BuiltinInspectorProps<Partial<CreateWorkArgs>, InspectorState>) => {+ const { t } = useTranslation('plugin');+ const params = args ?? partialArgs ?? {};+ const pending = isArgumentsStreaming || isLoading;++ const subject =+ pluginState?.work?.title?.trim() ||+ pluginState?.deleted?.title?.trim() ||+ (apiName === WorkApiName.deleteWork ? undefined : params.title?.trim());++ const failed = !pending && (!!pluginState?.error || !!result?.error);+ const imageCount = pending ? undefined : pluginState?.work?.imageCount;++ return (+ <div className={cx(inspectorTextStyles.root, pending && shinyTextStyles.shinyText)}>+ <span>{t(`builtins.lobe-work.apiName.${apiName}` as any)}</span>+ {subject && <span className={highlightTextStyles.primary}>{subject}</span>}+ {typeof imageCount === 'number' && !failed && (+ <Text+ as={'span'}+ color={cssVar.colorTextSecondary}+ fontSize={12}+ style={{ marginInlineStart: 6 }}+ >+ {t('builtins.lobe-work.inspector.images', { count: imageCount })}+ </Text>+ )}+ {failed && (+ <Text as={'span'} color={cssVar.colorError} fontSize={12} style={{ marginInlineStart: 6 }}>+ {t('builtins.lobe-work.inspector.failed')}+ </Text>+ )}+ </div>+ );+};++export const WorkInspectors: Record<string, BuiltinInspector> = Object.fromEntries(+ Object.values(WorkApiName).map((api) => [api, WorkInspector as BuiltinInspector]),+);diff --git a/packages/builtin-tool-work/src/client/index.ts b/packages/builtin-tool-work/src/client/index.tsnew file mode 100644index 00000000000..a826696fd46--- /dev/null+++ b/packages/builtin-tool-work/src/client/index.ts@@ -0,0 +1,3 @@+export { WorkManifest } from '../manifest';+export { WorkIdentifier } from '../types';+export { WorkInspectors } from './Inspector';diff --git a/packages/builtin-tool-work/src/index.ts b/packages/builtin-tool-work/src/index.tsnew file mode 100644index 00000000000..30ae3af64f4--- /dev/null+++ b/packages/builtin-tool-work/src/index.ts@@ -0,0 +1,3 @@+export { WorkManifest } from './manifest';+export { systemPrompt as WorkSystemPrompt } from './systemRole';+export * from './types';diff --git a/packages/builtin-tool-work/src/manifest.test.ts b/packages/builtin-tool-work/src/manifest.test.tsnew file mode 100644index 00000000000..7c3fab46591--- /dev/null+++ b/packages/builtin-tool-work/src/manifest.test.ts@@ -0,0 +1,26 @@+import { describe, expect, it } from 'vitest';++import { WorkManifest } from './manifest';+import { WorkApiName, WorkIdentifier } from './types';++describe('work tool manifest', () => {+ it('declares every API once, under the stable identifier', () => {+ expect(WorkManifest.identifier).toBe('lobe-work');+ expect(WorkIdentifier).toBe('lobe-work');+ expect(WorkManifest.api.map((entry) => entry.name).sort()).toEqual(+ Object.values(WorkApiName).sort(),+ );+ });++ it('runs without asking, including delete', () => {+ for (const entry of WorkManifest.api) expect(entry.humanIntervention, entry.name).toBe('never');+ });++ it('never takes the run from the model', () => {+ for (const entry of WorkManifest.api) {+ const properties = Object.keys(entry.parameters.properties ?? {});+ for (const forbidden of ['operationId', 'topicId', 'threadId', 'agentId', 'userId'])+ expect(properties).not.toContain(forbidden);+ }+ });+});diff --git a/packages/builtin-tool-work/src/manifest.ts b/packages/builtin-tool-work/src/manifest.tsnew file mode 100644index 00000000000..0dc42974c4a--- /dev/null+++ b/packages/builtin-tool-work/src/manifest.ts@@ -0,0 +1,96 @@+import type { BuiltinToolManifest } from '@lobechat/types';+import { COLLECTION_WORK_MAX_ITEMS } from '@lobechat/types';++import { systemPrompt } from './systemRole';+import { WorkApiName, WorkIdentifier } from './types';++const workId = {+ description: 'Id of a Work you created in this conversation, as createWork returned it (workId).',+ type: 'string',+} as const;++const items = {+ description:+ 'Collection images in display order. Each image is the generationId (gen_…) an image generation result lists, or a file id (file_…) or /f/file_… link.',+ items: {+ properties: {+ caption: { description: 'Short caption shown with the image.', type: 'string' },+ image: {+ description: 'generationId (gen_…), file id (file_…) or /f/file_… link of the image.',+ type: 'string',+ },+ },+ required: ['image'],+ type: 'object',+ },+ maxItems: COLLECTION_WORK_MAX_ITEMS,+ minItems: 1,+ type: 'array',+} as const;++const coverImage = {+ description: 'One of the items images to show on the card; defaults to the first image.',+ type: 'string',+} as const;++const description = { description: 'Short card description.', type: 'string' } as const;++export const WorkManifest: BuiltinToolManifest = {+ identifier: WorkIdentifier,+ type: 'builtin',+ systemRole: systemPrompt,+ meta: {+ avatar: '🗂️',+ title: 'Works',+ description:+ 'Show what you produced as a Work card under your reply: a collection of images (more media types later) or a published link. Change or delete Works you created.',+ },+ api: [+ {+ name: WorkApiName.createWork,+ humanIntervention: 'never',+ description:+ 'Create a Work card under your reply. type "collection" collects several images into one card; type "link" registers an http(s) page you published. Returns the workId.',+ parameters: {+ properties: {+ coverImage,+ description,+ items,+ title: { description: 'Card title.', type: 'string' },+ type: { enum: ['collection', 'link'], type: 'string' },+ url: { description: 'http(s) link; required for type "link".', type: 'string' },+ },+ required: ['type', 'title'],+ type: 'object',+ },+ },+ {+ name: WorkApiName.updateWork,+ humanIntervention: 'never',+ description:+ 'Save a new version of a Work you created. items replaces the whole image list of a collection; fields left out keep their values. A link keeps its URL.',+ parameters: {+ properties: {+ coverImage,+ description,+ items,+ title: { description: 'New card title.', type: 'string' },+ workId,+ },+ required: ['workId'],+ type: 'object',+ },+ },+ {+ name: WorkApiName.deleteWork,+ humanIntervention: 'never',+ description:+ 'Delete a Work you created by mistake. Removes the card and its versions; the images stay.',+ parameters: {+ properties: { workId },+ required: ['workId'],+ type: 'object',+ },+ },+ ],+};diff --git a/packages/builtin-tool-work/src/systemRole.ts b/packages/builtin-tool-work/src/systemRole.tsnew file mode 100644index 00000000000..0779bb7fe14--- /dev/null+++ b/packages/builtin-tool-work/src/systemRole.ts@@ -0,0 +1,10 @@+export const systemPrompt = `<lobe_work_guide>+A Work is a card under your reply that the user opens later and finds again in their library. Use these tools to register what you produced yourself.++- createWork type "collection": several images that belong to one deliverable (a set of covers, a storyboard, product shots). Put them all in ONE collection, in display order, instead of one Work per image. Name each image by the generationId (gen_…) the image generation tool listed, or by a file id (file_…) or /f/file_… link; add a short caption when it helps. Pick a cover with coverImage, or the first image is used.+- createWork type "link": an http(s) page you published, such as a deployed site. GitHub and Linear links become Works automatically when you create or edit them; never register them here.+- Keep the workId each call returns. To add, drop or reorder images, call updateWork with the complete new items list: it replaces the whole list. Title and description change only when you pass them.+- If you created a wrong Work (wrong images, duplicate, wrong link), call deleteWork with its workId, then create the right one. Deleting removes only the card; the images stay. A Work that is part of a goal, delivery or project cannot be deleted; update it instead.+- You can change or delete only Works you created in this conversation. Works collected automatically cannot be changed.+- Register only finished deliverables the user asked for; skip drafts and intermediate images.+</lobe_work_guide>`;diff --git a/packages/builtin-tool-work/src/types.ts b/packages/builtin-tool-work/src/types.tsnew file mode 100644index 00000000000..93bdf712564--- /dev/null+++ b/packages/builtin-tool-work/src/types.ts@@ -0,0 +1,76 @@+/** Permanent: stored in message history. */+export const WorkIdentifier = 'lobe-work';++export const WorkApiName = {+ createWork: 'createWork',+ deleteWork: 'deleteWork',+ updateWork: 'updateWork',+} as const;++export type WorkApiNameType = (typeof WorkApiName)[keyof typeof WorkApiName];++/** One collection image as the model names it. */+export interface WorkImageArg {+ caption?: string;+ /** A `generationId` (`gen_…`) from image generation, a file id (`file_…`) or a `/f/file_…` link. */+ image: string;+}++export interface CreateWorkArgs {+ /** One of `items[].image`; the first image when left out. Collection only. */+ coverImage?: string;+ description?: string;+ /** Collection images in display order. Required for a collection. */+ items?: WorkImageArg[];+ title: string;+ type: 'collection' | 'link';+ /** http(s) link. Required for a link. */+ url?: string;+}++export interface UpdateWorkArgs {+ coverImage?: string;+ description?: string;+ /** The complete new image list; replaces the current one. Collection only. */+ items?: WorkImageArg[];+ title?: string;+ workId: string;+}++export interface DeleteWorkArgs {+ workId: string;+}++/** A Work as the model and the inspector see it after a create or update. */+export interface WorkSummary {+ /** Number of images; collection only. */+ imageCount?: number;+ title: string | null;+ /** `file` only for a file Work the CLI created and this tool renamed. */+ type: 'collection' | 'file' | 'link';+ url?: string | null;+ workId: string;+}++export interface WorkState {+ work: WorkSummary;+}++export interface DeleteWorkState {+ deleted: { title: string | null; workId: string };+}++export const WORK_TOOL_ERROR_CODES = [+ 'conflict',+ 'forbidden',+ 'invalid_input',+ 'not_found',+ 'unavailable',+ 'unknown',+] as const;++export type WorkToolErrorCode = (typeof WORK_TOOL_ERROR_CODES)[number];++export interface WorkToolErrorState {+ error: { code: WorkToolErrorCode; message: string };+}diff --git a/packages/builtin-tool-work/vitest.config.mts b/packages/builtin-tool-work/vitest.config.mtsnew file mode 100644index 00000000000..cb61456dde1--- /dev/null+++ b/packages/builtin-tool-work/vitest.config.mts@@ -0,0 +1,3 @@+import { defineConfig } from 'vitest/config';++export default defineConfig({ test: { environment: 'node' } });diff --git a/packages/builtin-tools/package.json b/packages/builtin-tools/package.jsonindex 900d121f23a..d78d10f8524 100644--- a/packages/builtin-tools/package.json+++ b/packages/builtin-tools/package.json@@ -66,6 +66,7 @@"@lobechat/builtin-tool-web-browsing": "workspace:*","@lobechat/builtin-tool-web-onboarding": "workspace:*","@lobechat/builtin-tool-webhook": "workspace:*",+ "@lobechat/builtin-tool-work": "workspace:*","@lobechat/const": "workspace:*","@lobehub/icons": "^6.0.0"},diff --git a/packages/builtin-tools/src/identifiers.ts b/packages/builtin-tools/src/identifiers.tsindex fea398dcaf5..faef6f49a3f 100644--- a/packages/builtin-tools/src/identifiers.ts+++ b/packages/builtin-tools/src/identifiers.ts@@ -43,10 +43,12 @@ import { VideoGenerationManifest } from '@lobechat/builtin-tool-video-generationimport { WebBrowsingManifest } from '@lobechat/builtin-tool-web-browsing';import { WebOnboardingManifest } from '@lobechat/builtin-tool-web-onboarding';import { WebhookManifest } from '@lobechat/builtin-tool-webhook';+import { WorkManifest } from '@lobechat/builtin-tool-work';export const builtinToolIdentifiers: string[] = [McpEventsManifest.identifier,WebhookManifest.identifier,+ WorkManifest.identifier,ChannelManifest.identifier,AcceptanceEvidenceManifest.identifier,AgentBuilderManifest.identifier,diff --git a/packages/builtin-tools/src/index.ts b/packages/builtin-tools/src/index.tsindex 76635ac9c6c..0d6716aeddc 100644--- a/packages/builtin-tools/src/index.ts+++ b/packages/builtin-tools/src/index.ts@@ -58,6 +58,7 @@ import { VideoGenerationManifest } from '@lobechat/builtin-tool-video-generationimport { WebBrowsingManifest } from '@lobechat/builtin-tool-web-browsing';import { WebOnboardingManifest } from '@lobechat/builtin-tool-web-onboarding';import { WebhookManifest } from '@lobechat/builtin-tool-webhook';+import { WorkManifest } from '@lobechat/builtin-tool-work';import { isDesktop, RECOMMENDED_SKILLS, RecommendedSkillType } from '@lobechat/const';import {type AgentPluginEntry,@@ -275,8 +276,24 @@ export const AGENT_SHARE_ALLOWED_BUILTIN_IDENTIFIERS = new Set<string>([// API of the tool is blocked. See the allowed-builtins section of// `shareGate/README.md`.SkillsManifest.identifier,+ // `lobe-work`: on in every visitor run without a creator grant (see+ // {@link AGENT_SHARE_IMPLIED_BUILTIN_IDENTIFIERS}). Its runtime takes the run+ // (operation, topic, tool call) from the execution context only, writes under+ // the share scope pinned to the visitor topic (`resolveRunWorkAccessScope`),+ // and changes or deletes only Works this conversation created. Collection images+ // must be generated images or run outputs (`resolveAgentWorkCollectionItems`).+ // See the allowed-builtins section of `shareGate/README.md`.+ WorkManifest.identifier,]);+/**+ * Builtins every share visitor run gets without an owner grant: the server+ * implies their grant (`resolveEffectiveShareToolGrants`) and enables them+ * (`getShareGrantActivatedPluginIds`). The owner share-settings picker leaves+ * them out, since a toggle there would change nothing.+ */+export const AGENT_SHARE_IMPLIED_BUILTIN_IDENTIFIERS = new Set<string>([WorkManifest.identifier]);+/*** Subset of {@link AGENT_SHARE_ALLOWED_BUILTIN_IDENTIFIERS} whose server-side* data grant is UNCONDITIONALLY `none` — surviving the master allowlist only@@ -462,6 +479,15 @@ const builtinToolRegistry: LobeBuiltinTool[] = [manifest: WebhookManifest,type: 'builtin',},+ {+ // On demand: hidden and absent from the defaults, but discoverable, so the activator enables+ // it when the agent has a collection or a published link to show. A share visitor's run gets it+ // without a creator grant (see `shareGate/grants.ts`): its Works stay in the visitor's topic.+ hidden: true,+ identifier: WorkManifest.identifier,+ manifest: WorkManifest,+ type: 'builtin',+ },{hidden: true,identifier: KnowledgeBaseManifest.identifier,diff --git a/packages/builtin-tools/src/register.ts b/packages/builtin-tools/src/register.tsindex cbf9eefbfb0..57c9c1782c4 100644--- a/packages/builtin-tools/src/register.ts+++ b/packages/builtin-tools/src/register.ts@@ -193,6 +193,7 @@ import {WebhookInterventions,WebhookRenders,} from '@lobechat/builtin-tool-webhook/client';+import { WorkIdentifier, WorkInspectors } from '@lobechat/builtin-tool-work/client';import {createEditLocalFileInspector,createReadLocalFileInspector,@@ -404,6 +405,7 @@ export const registerBuiltinToolSurfaces = (): void => {[LocalSystemManifest.identifier]: LocalSystemInspectors as Record<string, BuiltinInspector>,[McpEventsIdentifier]: McpEventsInspectors,[WebhookIdentifier]: WebhookInspectors,+ [WorkIdentifier]: WorkInspectors,[MemoryManifest.identifier]: MemoryInspectors as Record<string, BuiltinInspector>,[MessageManifest.identifier]: MessageInspectors as Record<string, BuiltinInspector>,[PageAgentManifest.identifier]: PageAgentInspectors as Record<string, BuiltinInspector>,diff --git a/packages/builtin-tools/src/serverOnly.ts b/packages/builtin-tools/src/serverOnly.tsindex 09072a5e9f6..1b18635061d 100644--- a/packages/builtin-tools/src/serverOnly.ts+++ b/packages/builtin-tools/src/serverOnly.ts@@ -1,9 +1,14 @@import { McpEventsIdentifier } from '@lobechat/builtin-tool-mcp-events';import { WebhookIdentifier } from '@lobechat/builtin-tool-webhook';+import { WorkIdentifier } from '@lobechat/builtin-tool-work';/*** Builtin tools only the server runtime can execute: they have no browser executor (their work* needs the database and stored credentials). A run the browser drives itself (no agent gateway,* or gateway mode turned off) leaves them out, or a call would come back empty.*/-export const serverOnlyToolIds: readonly string[] = [McpEventsIdentifier, WebhookIdentifier];+export const serverOnlyToolIds: readonly string[] = [+ McpEventsIdentifier,+ WebhookIdentifier,+ WorkIdentifier,+];diff --git a/packages/builtin-tools/src/workRegistration.test.ts b/packages/builtin-tools/src/workRegistration.test.tsindex 355e5acd105..daed08c6b27 100644--- a/packages/builtin-tools/src/workRegistration.test.ts+++ b/packages/builtin-tools/src/workRegistration.test.ts@@ -163,6 +163,55 @@ describe('resolveWorkRegistration', () => {});});+ it('carries agentEditable only when the API work config declares it', () => {+ const editable = [+ {+ identifier: 'lobe-task',+ manifest: {+ api: [+ {+ name: 'createTask',+ work: { action: 'create', agentEditable: true, resourceType: 'task' },+ },+ ],+ },+ },+ {+ identifier: 'lobe-agent-documents',+ manifest: {+ api: [+ {+ name: 'createDocument',+ work: { action: 'create', agentEditable: true, resourceType: 'document' },+ },+ ],+ },+ },+ ] as unknown as LobeBuiltinTool[];+ const taskCall = {+ args: {},+ result: { state: { taskId: 'task_1', success: true }, success: true },+ };+ const documentCall = {+ args: {},+ result: {+ state: { agentId: 'agt_1', documentId: 'doc_1', success: true },+ success: true,+ },+ };++ expect(resolveWorkRegistration(editable, 'lobe-task', 'createTask', taskCall)).toMatchObject({+ agentEditable: true,+ });+ expect(+ resolveWorkRegistration(editable, 'lobe-agent-documents', 'createDocument', documentCall),+ ).toMatchObject({ document: { agentEditable: true } });+ // Undeclared stays off the intent, so Works default to system-owned.+ expect(+ resolveWorkRegistration(registry, 'lobe-task', 'createTask', taskCall),+ ).not.toHaveProperty('agentEditable');+ });+it('resolves delete into a changeType-less plan keyed off state.taskId', () => {expect(resolveWorkRegistration(registry, 'lobe-task', 'deleteTask', {@@ -381,6 +430,28 @@ describe('dispatchWorkRegistrationIntent', () => {2,expect.objectContaining({ taskId: 'task_2', taskIdentifier: 'T-2' }),);+ expect(ports.registerTask).not.toHaveBeenCalledWith(+ expect.objectContaining({ agentEditable: expect.anything() }),+ );+ });++ it('passes agentEditable through to every registered task', async () => {+ const ports = buildPorts();+ await dispatchWorkRegistrationIntent(+ {+ action: 'create',+ agentEditable: true,+ changeType: 'created',+ targets: [{ taskId: 'task_1' }],+ type: 'task',+ },+ ports,+ provenance,+ );++ expect(ports.registerTask).toHaveBeenCalledWith(+ expect.objectContaining({ agentEditable: true, taskId: 'task_1' }),+ );});it('deletes each target that has a taskId and skips targetless ids', async () => {diff --git a/packages/builtin-tools/src/workRegistration.ts b/packages/builtin-tools/src/workRegistration.tsindex abfe5756bf1..9248e28b3a0 100644--- a/packages/builtin-tools/src/workRegistration.ts+++ b/packages/builtin-tools/src/workRegistration.ts@@ -217,6 +217,7 @@ const resolveTaskWorkIntent = ({return {action: config.action,+ ...(config.agentEditable && { agentEditable: true }),changeType: workChangeTypeFromAction(config.action),targets,type: 'task',@@ -239,6 +240,7 @@ const resolveDocumentWorkIntent = ({action: 'register',document: {...document,+ ...(config.agentEditable && { agentEditable: true }),changeType: workChangeTypeFromAction(config.action),// The concrete API name is the document Work's producing tool.toolName: apiName,@@ -360,7 +362,7 @@ const dispatchTaskWorkIntent = async (toolName,topicId,} = provenance;- const { action, changeType, targets } = intent;+ const { action, agentEditable, changeType, targets } = intent;if (action === 'delete') {const deleteTargets = targets.filter((target) => target.taskId);@@ -376,6 +378,7 @@ const dispatchTaskWorkIntent = async (const results = await Promise.allSettled(targets.map((target) =>ports.registerTask({+ ...(agentEditable && { agentEditable }),agentId,changeType,cumulativeCost,diff --git a/packages/database/src/models/__tests__/agentShareProfile.test.ts b/packages/database/src/models/__tests__/agentShareProfile.test.tsindex 2de2a7c5a37..a1ed2390fe3 100644--- a/packages/database/src/models/__tests__/agentShareProfile.test.ts+++ b/packages/database/src/models/__tests__/agentShareProfile.test.ts@@ -148,6 +148,54 @@ describe('AgentShareProfileModel', () => {expect(items[1].url).toBe('https://github.com/example/repo/issues/1');});+ it('features a collection with its cover and the current version images', async () => {+ const version = await addWork('collection', {+ type: 'collection',+ resourceType: 'collection',+ resourceId: 'col_1',+ url: 'https://app.example.com/f/file-2',+ });+ await db+ .update(workVersions)+ .set({+ metadata: {+ collection: {+ coverFileId: 'file-2',+ items: [+ {+ caption: 'Apple',+ fileId: 'file-1',+ mimeType: 'image/png',+ url: 'https://app.example.com/f/file-1',+ },+ { fileId: 'file-2', mimeType: 'image/png', url: 'https://app.example.com/f/file-2' },+ { fileId: 'file-3', url: 'javascript:alert(1)' },+ ],+ },+ },+ })+ .where(eq(workVersions.id, version.id));++ const [featured] = await model.listFeaturedWorks(agent, ['collection']);+ expect(featured).toMatchObject({ type: 'collection', url: 'https://app.example.com/f/file-2' });+ // Only http(s) images are exposed.+ expect(featured.collection).toEqual({+ coverFileId: 'file-2',+ items: [+ {+ caption: 'Apple',+ fileId: 'file-1',+ mimeType: 'image/png',+ url: 'https://app.example.com/f/file-1',+ },+ { fileId: 'file-2', mimeType: 'image/png', url: 'https://app.example.com/f/file-2' },+ ],+ });++ const { items } = await model.listEligibleWorks(agent);+ expect(items.find(({ id }) => id === 'collection')?.collection?.items).toHaveLength(2);+ });+it('pages creator candidates and keeps selected Works available outside the page', async () => {await addWork('newest');await addWork('middle');diff --git a/packages/database/src/models/__tests__/messages/message.query.test.ts b/packages/database/src/models/__tests__/messages/message.query.test.tsindex 9932a5d5aff..751bc3cbb6d 100644--- a/packages/database/src/models/__tests__/messages/message.query.test.ts+++ b/packages/database/src/models/__tests__/messages/message.query.test.ts@@ -1893,7 +1893,7 @@ describe('MessageModel Query Tests', () => {{ allowShareVisitor: true },);- expect(findAnchor(result).works).toBeUndefined();+ expect(findAnchor(result).works).toEqual([]);});});diff --git a/packages/database/src/models/agentShareProfile.ts b/packages/database/src/models/agentShareProfile.tsindex a0bf084bfc5..fa713b8a260 100644--- a/packages/database/src/models/agentShareProfile.ts+++ b/packages/database/src/models/agentShareProfile.ts@@ -1,4 +1,9 @@-import type { SharedAgentDeliveryStats, SharedAgentWork } from '@lobechat/types';+import type {+ CollectionWorkVersionMetadata,+ SharedAgentDeliveryStats,+ SharedAgentWork,+ WorkVersionMetadata,+} from '@lobechat/types';import { TRPCError } from '@trpc/server';import {and,@@ -43,6 +48,26 @@ const inAgentScope = (workspaceId: AnyColumn) =>const outsideAgentScope = (workspaceId: AnyColumn) =>sql`${workspaceId} is distinct from ${agents.workspaceId}`;+/**+ * The images of a collection Work, the only file links a share profile exposes:+ * featuring a collection is choosing to show its images. Each keeps only an+ * http(s) URL.+ */+const toSharedCollection = (+ metadata: WorkVersionMetadata | null,+): CollectionWorkVersionMetadata | undefined => {+ const collection = metadata?.collection;+ if (!collection) return undefined;+ const items = collection.items.flatMap(({ caption, fileId, mimeType, url }) => {+ const safeUrl = sanitizeExternalUrl(url);+ if (!safeUrl) return [];+ return [+ { ...(caption ? { caption } : {}), fileId, ...(mimeType ? { mimeType } : {}), url: safeUrl },+ ];+ });+ return { ...(collection.coverFileId ? { coverFileId: collection.coverFileId } : {}), items };+};+/** Owner-scoped source for explicitly curated share profiles, not a general resource grant. */export class AgentShareProfileModel {constructor(@@ -71,6 +96,7 @@ export class AgentShareProfileModel {type: works.type,updatedAt: works.updatedAt,url: works.url,+ versionMetadata: workVersions.metadata,}).from(works).innerJoin(agents, eq(agents.id, works.originAgentId))@@ -119,7 +145,7 @@ export class AgentShareProfileModel {),ids ? inArray(works.id, ids) : undefined,or(- inArray(works.type, ['external', 'file']),+ inArray(works.type, ['external', 'file', 'collection']),and(eq(works.type, 'document'),exists(@@ -177,15 +203,26 @@ export class AgentShareProfileModel {rows.map(({ id }) => id),);const byId = new Map(- rows.map(({ deliveredAt: _deliveredAt, ...work }) => [- work.id,- {- ...work,- totalCost: costs.get(work.id) ?? null,- /** File URLs can be bearer download links; featuring a Work is not a download grant. */- url: work.type === 'external' ? (sanitizeExternalUrl(work.url) ?? null) : null,- },- ]),+ rows.map(({ deliveredAt: _deliveredAt, versionMetadata, ...work }) => {+ const collection =+ work.type === 'collection' ? toSharedCollection(versionMetadata) : undefined;+ return [+ work.id,+ {+ ...work,+ ...(collection ? { collection } : {}),+ totalCost: costs.get(work.id) ?? null,+ /**+ * File URLs can be bearer download links; featuring a file Work is not a+ * download grant. A collection's URL is its cover, shown with its images.+ */+ url:+ work.type === 'external' || work.type === 'collection'+ ? (sanitizeExternalUrl(work.url) ?? null)+ : null,+ },+ ];+ }),);return workIds.flatMap((id) => {const work = byId.get(id);@@ -225,14 +262,19 @@ export class AgentShareProfileModel {allRows.map(({ id }) => id),);const byId = new Map(- allRows.map(({ deliveredAt: _deliveredAt, ...work }) => [- work.id,- {- ...work,- totalCost: costs.get(work.id) ?? null,- url: sanitizeExternalUrl(work.url) ?? null,- },- ]),+ allRows.map(({ deliveredAt: _deliveredAt, versionMetadata, ...work }) => {+ const collection =+ work.type === 'collection' ? toSharedCollection(versionMetadata) : undefined;+ return [+ work.id,+ {+ ...work,+ ...(collection ? { collection } : {}),+ totalCost: costs.get(work.id) ?? null,+ url: sanitizeExternalUrl(work.url) ?? null,+ },+ ];+ }),);const orderedIds = [...includeWorkIds, ...pageRows.map(({ id }) => id)];diff --git a/packages/database/src/models/message/relations.ts b/packages/database/src/models/message/relations.tsindex bc3dc7fe106..9534f639b42 100644--- a/packages/database/src/models/message/relations.ts+++ b/packages/database/src/models/message/relations.ts@@ -237,11 +237,13 @@ export class MessageRelationQueries extends MessageScope {const worksByMessageId: Record<string, WorkSummaryItem[]> = {};for (const [rootOperationId, messageId] of anchorByRootId) {- const works = summaryMap[rootOperationId];- if (works && works.length > 0) worksByMessageId[messageId] = works;+ // An anchor whose Works are all gone gets an explicit empty list: clients+ // keep the previous `works` only when a payload omits it (a skipWorks+ // read), so omitting it here would revive a deleted Work card.+ worksByMessageId[messageId] = summaryMap[rootOperationId] ?? [];}logTiming(timing, 'db.message.queryWithWhere.workSummaries:rows', {- messageCount: Object.keys(worksByMessageId).length,+ messageCount: Object.values(worksByMessageId).filter((works) => works.length > 0).length,});return worksByMessageId;};diff --git a/packages/database/src/models/work/__tests__/agentWork.collection.test.ts b/packages/database/src/models/work/__tests__/agentWork.collection.test.tsnew file mode 100644index 00000000000..3775fd9c32c--- /dev/null+++ b/packages/database/src/models/work/__tests__/agentWork.collection.test.ts@@ -0,0 +1,300 @@+// @vitest-environment node+import type { AgentWorkRunContext, CollectionWorkItem } from '@lobechat/types';+import { eq } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { topics, works, workVersions } from '../../../schemas';+import { AgentWorkError, WorkModel } from '..';+import {+ agentId,+ cleanupWorkTestData,+ seedWorkTestData,+ serverDB,+ threadId,+ topicId,+ userId,+ userId2,+} from './_fixtures';++beforeEach(seedWorkTestData);+afterEach(cleanupWorkTestData);++const run: AgentWorkRunContext = {+ agentId,+ messageId: null,+ operationId: 'op-collection',+ threadId,+ toolCallId: 'call-collection-1',+ toolIdentifier: 'lobe-work',+ topicId,+ userId,+};++const image = (n: number, caption?: string): CollectionWorkItem => ({+ caption,+ fileId: `file-cd-${n}`,+ mimeType: 'image/png',+ url: `https://app.example.com/f/file-cd-${n}`,+});++const workModel = () => new WorkModel(serverDB, userId);++const expectAgentWorkError = async (promise: Promise<unknown>, code: AgentWorkError['code']) => {+ const error = await promise.catch((caught: unknown) => caught);+ expect(error).toBeInstanceOf(AgentWorkError);+ expect((error as AgentWorkError).code).toBe(code);+};++const createCollection = (overrides: Partial<AgentWorkRunContext> = {}) =>+ workModel().createAgentWork(+ { ...run, ...overrides },+ {+ coverFileId: 'file-cd-2',+ items: [image(1, 'Apple'), image(2, 'Microsoft')],+ title: 'Top ten CD shelf',+ type: 'collection',+ },+ );++describe('WorkModel · agent collections', () => {+ it('creates a collection whose card shows the cover and whose version holds every image', async () => {+ const work = await createCollection();++ expect(work).toMatchObject({+ resourceType: 'collection',+ title: 'Top ten CD shelf',+ toolIdentifier: 'lobe-work',+ type: 'collection',+ url: 'https://app.example.com/f/file-cd-2',+ });+ expect(work.resourceId).toMatch(/^col_/);+ const [row] = await serverDB.select().from(works).where(eq(works.id, work.id));+ expect(row.metadata).toEqual({ agentEditable: true });++ const [version] = await workModel().listVersions(work.id);+ expect(version).toMatchObject({+ changeType: 'created',+ rootOperationId: run.operationId,+ toolCallId: run.toolCallId,+ });+ expect(version.metadata?.collection).toEqual({+ coverFileId: 'file-cd-2',+ items: [+ { caption: 'Apple', fileId: 'file-cd-1', mimeType: 'image/png', url: image(1).url },+ { caption: 'Microsoft', fileId: 'file-cd-2', mimeType: 'image/png', url: image(2).url },+ ],+ });++ // The reply's Work card is found through the run's operation, opted-in clients only.+ const listed = await workModel().listByRootOperation({+ includeFileWorks: true,+ rootOperationId: run.operationId,+ });+ expect(listed.map((item) => item.id)).toEqual([work.id]);+ const legacy = await workModel().listByRootOperation({ rootOperationId: run.operationId });+ expect(legacy).toEqual([]);+ });++ it('makes every create a new collection', async () => {+ const first = await createCollection();+ const second = await createCollection({ toolCallId: 'call-collection-2' });+ expect(second.id).not.toBe(first.id);+ });++ it('rejects an empty list, repeated images and a cover outside the list', async () => {+ for (const collection of [+ { items: [] },+ { items: [image(1), image(1)] },+ { coverFileId: 'file-cd-9', items: [image(1)] },+ ]) {+ await expectAgentWorkError(+ workModel().createAgentWork(run, { ...collection, title: 'Bad', type: 'collection' }),+ 'BAD_REQUEST',+ );+ }+ expect(await serverDB.select().from(works)).toEqual([]);+ });++ it('caps the text a model writes and refuses an empty title on update', async () => {+ await expectAgentWorkError(+ workModel().createAgentWork(run, {+ items: [{ ...image(1), caption: 'x'.repeat(501) }],+ title: 'Shelf',+ type: 'collection',+ }),+ 'BAD_REQUEST',+ );+ await expectAgentWorkError(+ workModel().createAgentWork(run, {+ title: 'x'.repeat(201),+ type: 'link',+ url: 'https://preview.example.com',+ }),+ 'BAD_REQUEST',+ );+ const collection = await createCollection();+ for (const patch of [{ title: ' ' }, { description: 'x'.repeat(2001) }]) {+ await expectAgentWorkError(+ workModel().updateAgentWork(run, { ...patch, workId: collection.id }),+ 'BAD_REQUEST',+ );+ }+ });++ it('replaces the whole image list on update and keeps the title', async () => {+ const created = await createCollection();++ const updated = await workModel().updateAgentWork(+ { ...run, toolCallId: 'call-collection-update' },+ { collection: { items: [image(3, 'Nvidia'), image(1, 'Apple')] }, workId: created.id },+ );++ // No cover named: the first image becomes the cover.+ expect(updated).toMatchObject({ title: 'Top ten CD shelf', url: image(3).url });+ const versions = await workModel().listVersions(created.id);+ expect(versions).toHaveLength(2);+ const latest = versions.find((version) => version.changeType === 'updated');+ expect(latest?.metadata?.collection).toEqual({+ items: [+ { caption: 'Nvidia', fileId: 'file-cd-3', mimeType: 'image/png', url: image(3).url },+ { caption: 'Apple', fileId: 'file-cd-1', mimeType: 'image/png', url: image(1).url },+ ],+ });++ const renamed = await workModel().updateAgentWork(+ { ...run, toolCallId: 'call-collection-rename' },+ { title: 'Shelf v2', workId: created.id },+ );+ expect(renamed).toMatchObject({ title: 'Shelf v2', url: image(3).url });+ const [, , third] = (await workModel().listVersions(created.id)).sort(+ (a, b) => a.version - b.version,+ );+ // A title-only update carries the images over.+ expect(third.metadata?.collection?.items.map((item) => item.fileId)).toEqual([+ 'file-cd-3',+ 'file-cd-1',+ ]);+ });++ it('gives images only to a collection, and a collection no file', async () => {+ const collection = await createCollection();+ const link = await workModel().createAgentWork(run, {+ title: 'Preview',+ type: 'link',+ url: 'https://preview.example.com',+ });++ await expectAgentWorkError(+ workModel().updateAgentWork(run, { collection: { items: [image(1)] }, workId: link.id }),+ 'BAD_REQUEST',+ );+ await expectAgentWorkError(+ workModel().updateAgentWork(run, {+ file: { fileId: 'file-x', fileUrl: 'https://app.example.com/f/file-x' },+ workId: collection.id,+ }),+ 'BAD_REQUEST',+ );+ });+});++describe('WorkModel · deleting agent Works', () => {+ it('removes the Work card and its versions', async () => {+ const collection = await createCollection();+ await workModel().updateAgentWork(+ { ...run, toolCallId: 'call-collection-update' },+ { title: 'Renamed', workId: collection.id },+ );++ expect(await workModel().deleteAgentWork(run, collection.id)).toEqual({+ id: collection.id,+ title: 'Renamed',+ });+ expect(await serverDB.select().from(works).where(eq(works.id, collection.id))).toEqual([]);+ expect(+ await serverDB.select().from(workVersions).where(eq(workVersions.workId, collection.id)),+ ).toEqual([]);+ });++ it('deletes a link Work the agent created', async () => {+ const link = await workModel().createAgentWork(run, {+ title: 'Wrong link',+ type: 'link',+ url: 'https://wrong.example.com',+ });+ await workModel().deleteAgentWork(run, link.id);+ expect(await serverDB.select().from(works)).toEqual([]);+ });++ it('refuses a Work registered automatically', async () => {+ const scanned = await workModel().registerFile({+ filePath: '/mnt/data/deck.pptx',+ metadata: { fileId: 'file-deck', filePath: '/mnt/data/deck.pptx' },+ rootOperationId: 'op-scan',+ title: 'deck.pptx',+ toolCallId: 'op:op-scan',+ toolIdentifier: 'lobe-cloud-sandbox',+ toolName: 'writeFile',+ topicId,+ userId,+ });++ await expectAgentWorkError(workModel().deleteAgentWork(run, scanned.id), 'FORBIDDEN');+ expect(await serverDB.select().from(works).where(eq(works.id, scanned.id))).toHaveLength(1);+ });++ it('refuses a run in another conversation or of another user', async () => {+ const collection = await createCollection();+ const otherTopicId = 'work-collection-other-topic';+ await serverDB.insert(topics).values({ id: otherTopicId, userId });++ await expectAgentWorkError(+ workModel().deleteAgentWork({ ...run, topicId: otherTopicId }, collection.id),+ 'NOT_FOUND',+ );+ await expectAgentWorkError(+ new WorkModel(serverDB, userId2).deleteAgentWork({ ...run, userId: userId2 }, collection.id),+ 'NOT_FOUND',+ );+ expect(await serverDB.select().from(works).where(eq(works.id, collection.id))).toHaveLength(1);+ });++ it("gives the run's agent-written versions the run total once the run ends", async () => {+ const collection = await createCollection();+ await workModel().updateAgentWork(+ { ...run, toolCallId: 'call-collection-2' },+ { title: 'Renamed shelf', workId: collection.id },+ );+ const scanned = await workModel().registerFile({+ cumulativeCost: 0.01,+ filePath: '/mnt/data/deck.pptx',+ metadata: { fileId: 'file-deck', filePath: '/mnt/data/deck.pptx' },+ rootOperationId: 'op-collection',+ title: 'deck.pptx',+ toolCallId: 'op:op-collection',+ toolIdentifier: 'lobe-cloud-sandbox',+ toolName: 'writeFile',+ topicId,+ userId,+ });++ const fill = () =>+ workModel().fillAgentWorkCost({+ cumulativeCost: 0.25,+ cumulativeUsage: null,+ rootOperationId: 'op-collection',+ });+ expect(await fill()).toBe(2);+ // A retried completion changes nothing.+ expect(await fill()).toBe(0);++ const costs = await serverDB+ .select({ cost: workVersions.cumulativeCost, workId: workVersions.workId })+ .from(workVersions);+ expect(costs.filter((row) => row.workId === collection.id).map((row) => row.cost)).toEqual([+ 0.25, 0.25,+ ]);+ // A Work that already carries its own cost keeps it.+ expect(costs.find((row) => row.workId === scanned!.id)?.cost).toBe(0.01);+ });+});diff --git a/packages/database/src/models/work/__tests__/agentWork.test.ts b/packages/database/src/models/work/__tests__/agentWork.test.tsnew file mode 100644index 00000000000..51dd20e16cf--- /dev/null+++ b/packages/database/src/models/work/__tests__/agentWork.test.ts@@ -0,0 +1,398 @@+// @vitest-environment node+import type { AgentWorkRunContext } from '@lobechat/types';+import { AGENT_WORK_CLI_TOOL_IDENTIFIER } from '@lobechat/types';+import { eq } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { goalNodes, goalNodeWorkVersions, topics, works, workspaces } from '../../../schemas';+import { GoalModel } from '../../goal';+import { TaskModel } from '../../task';+import { AgentWorkError, WorkModel } from '..';+import { linkWorkResourceId } from '../agentWork';+import { fileWorkResourceId } from '../file';+import {+ agentId,+ cleanupWorkTestData,+ seedWorkTestData,+ serverDB,+ threadId,+ topicId,+ userId,+ userId2,+} from './_fixtures';++beforeEach(seedWorkTestData);+afterEach(cleanupWorkTestData);++const run: AgentWorkRunContext = {+ agentId,+ operationId: 'op-agent-work',+ threadId,+ topicId,+ userId,+ userId2,+};++const reportFile = {+ fileId: 'file-report-1',+ filePath: '/workspace/out/report.pdf',+ fileSize: 1024,+ fileUrl: 'https://app.example.com/f/file-report-1',+ mimeType: 'application/pdf',+};++const workModel = () => new WorkModel(serverDB, userId);++const storedMetadata = async (workId: string) => {+ const [row] = await serverDB.select().from(works).where(eq(works.id, workId));+ return row.metadata;+};++const expectAgentWorkError = async (promise: Promise<unknown>, code: AgentWorkError['code']) => {+ const error = await promise.catch((caught: unknown) => caught);+ expect(error).toBeInstanceOf(AgentWorkError);+ expect((error as AgentWorkError).code).toBe(code);+};++describe('WorkModel · agent-created Works', () => {+ it('registers a link the agent produced under the running operation', async () => {+ const work = await workModel().createAgentWork(run, {+ description: 'Preview deployment',+ title: 'Landing preview',+ type: 'link',+ url: 'https://preview.example.com/landing',+ });++ expect(work).toMatchObject({+ description: 'Preview deployment',+ resourceId: linkWorkResourceId(userId, topicId, 'https://preview.example.com/landing'),+ resourceType: 'link',+ title: 'Landing preview',+ toolIdentifier: AGENT_WORK_CLI_TOOL_IDENTIFIER,+ type: 'external',+ url: 'https://preview.example.com/landing',+ });+ expect(await storedMetadata(work.id)).toEqual({ agentEditable: true });++ // The completion lifecycle anchors the card through the run's operation id.+ const listed = await workModel().listByRootOperation({ rootOperationId: run.operationId });+ expect(listed.map((item) => item.id)).toEqual([work.id]);+ });++ it('refuses GitHub and Linear links and non-http(s) URLs', async () => {+ for (const url of [+ 'https://github.com/owner/repo/pull/1',+ 'https://gist.github.com/owner/abc',+ 'https://linear.app/team/issue/LOBE-1',+ 'javascript:alert(1)',+ ]) {+ await expectAgentWorkError(+ workModel().createAgentWork(run, { title: 'x', type: 'link', url }),+ 'BAD_REQUEST',+ );+ }+ expect(await serverDB.select().from(works)).toEqual([]);+ });++ it('registers a file with the file name as the default title', async () => {+ const work = await workModel().createAgentWork(run, { file: reportFile, type: 'file' });++ expect(work).toMatchObject({+ description: reportFile.filePath,+ resourceId: fileWorkResourceId(userId, topicId, reportFile.filePath),+ title: 'report.pdf',+ type: 'file',+ });+ expect(await storedMetadata(work.id)).toEqual({ agentEditable: true });+ const [version] = await workModel().listVersions(work.id);+ expect(version).toMatchObject({+ changeType: 'created',+ metadata: expect.objectContaining({ fileId: 'file-report-1', mimeType: 'application/pdf' }),+ rootOperationId: run.operationId,+ });+ });++ it('adds a version when the agent creates the same file path again', async () => {+ const first = await workModel().createAgentWork(run, { file: reportFile, type: 'file' });+ const second = await workModel().createAgentWork(run, {+ file: { ...reportFile, fileId: 'file-report-2' },+ title: 'Q3 report',+ type: 'file',+ });++ expect(second.id).toBe(first.id);+ expect(second.title).toBe('Q3 report');+ expect(await workModel().listVersions(first.id)).toHaveLength(2);+ });++ it('refuses to take over a file the completion scan registered', async () => {+ await workModel().registerFile({+ filePath: reportFile.filePath,+ metadata: { fileId: 'file-scanned', filePath: reportFile.filePath },+ rootOperationId: 'op-scan',+ title: 'report.pdf',+ toolCallId: 'op:op-scan',+ toolIdentifier: 'lobe-cloud-sandbox',+ toolName: 'writeFile',+ topicId,+ userId,+ });++ await expectAgentWorkError(+ workModel().createAgentWork(run, { file: reportFile, type: 'file' }),+ 'CONFLICT',+ );+ });++ it('updates only the fields given and keeps the rest', async () => {+ const created = await workModel().createAgentWork(run, {+ description: 'First draft',+ title: 'Landing preview',+ type: 'link',+ url: 'https://preview.example.com/v1',+ });++ const updated = await workModel().updateAgentWork(run, {+ description: 'Second draft',+ workId: created.id,+ });+ expect(updated).toMatchObject({+ description: 'Second draft',+ id: created.id,+ title: 'Landing preview',+ url: 'https://preview.example.com/v1',+ });++ const versions = await workModel().listVersions(created.id);+ expect(versions).toHaveLength(2);+ expect(versions.filter((version) => version.changeType === 'updated')).toHaveLength(1);++ // The link stays its identity: creating it again adds to the same Work.+ const again = await workModel().createAgentWork(run, {+ title: 'Landing preview',+ type: 'link',+ url: 'https://preview.example.com/v1',+ });+ expect(again.id).toBe(created.id);+ });++ it('replaces the file of a file Work', async () => {+ const created = await workModel().createAgentWork(run, { file: reportFile, type: 'file' });++ const updated = await workModel().updateAgentWork(run, {+ file: { ...reportFile, fileId: 'file-report-2', fileUrl: 'https://app.example.com/f/2' },+ workId: created.id,+ });++ expect(updated).toMatchObject({ title: 'report.pdf', url: 'https://app.example.com/f/2' });+ const versions = await workModel().listVersions(created.id);+ expect(versions.map((version) => version.metadata?.fileId)).toContain('file-report-2');+ });++ it('refuses to update a Work registered automatically', async () => {+ const scanned = await workModel().registerFile({+ filePath: '/mnt/data/deck.pptx',+ metadata: { fileId: 'file-deck', filePath: '/mnt/data/deck.pptx' },+ rootOperationId: 'op-scan',+ title: 'deck.pptx',+ toolCallId: 'op:op-scan',+ toolIdentifier: 'lobe-cloud-sandbox',+ toolName: 'writeFile',+ topicId,+ userId,+ });++ await expectAgentWorkError(+ workModel().updateAgentWork(run, { title: 'Renamed', workId: scanned.id }),+ 'FORBIDDEN',+ );+ });++ it('rejects updates that do not fit the Work', async () => {+ const link = await workModel().createAgentWork(run, {+ title: 'Preview',+ type: 'link',+ url: 'https://preview.example.com',+ });++ await expectAgentWorkError(+ workModel().updateAgentWork(run, { file: reportFile, workId: link.id }),+ 'BAD_REQUEST',+ );+ await expectAgentWorkError(+ workModel().updateAgentWork(run, { workId: link.id }),+ 'BAD_REQUEST',+ );+ await expectAgentWorkError(+ workModel().updateAgentWork(run, { title: 'x', workId: 'missing-work' }),+ 'NOT_FOUND',+ );+ });++ it('keeps a Work of another user out of reach', async () => {+ const created = await workModel().createAgentWork(run, {+ title: 'Preview',+ type: 'link',+ url: 'https://preview.example.com',+ });++ await expectAgentWorkError(+ new WorkModel(serverDB, userId2).updateAgentWork(+ { ...run, userId: userId2 },+ { title: 'Hijacked', workId: created.id },+ ),+ 'NOT_FOUND',+ );+ });++ it('lets only runs in a conversation that produced the Work update it', async () => {+ const otherTopicId = 'work-agent-other-topic';+ await serverDB.insert(topics).values({ id: otherTopicId, userId });+ const otherRun = { ...run, operationId: 'op-other', topicId: otherTopicId };+ const created = await workModel().createAgentWork(run, {+ title: 'Preview',+ type: 'link',+ url: 'https://preview.example.com',+ });++ await expectAgentWorkError(+ workModel().updateAgentWork(otherRun, { title: 'Renamed', workId: created.id }),+ 'NOT_FOUND',+ );++ // The same link in another conversation is a Work of that conversation, so+ // that run still cannot reach the first one through it.+ const again = await workModel().createAgentWork(otherRun, {+ title: 'Preview',+ type: 'link',+ url: 'https://preview.example.com',+ });+ expect(again.id).not.toBe(created.id);+ await expectAgentWorkError(+ workModel().updateAgentWork(otherRun, { title: 'Renamed', workId: created.id }),+ 'NOT_FOUND',+ );+ await expectAgentWorkError(workModel().deleteAgentWork(otherRun, created.id), 'NOT_FOUND');+ expect((await workModel().listVersions(created.id)).length).toBe(1);++ // In its own conversation, registering the link again adds a version.+ const repeat = await workModel().createAgentWork(run, {+ title: 'Preview v2',+ type: 'link',+ url: 'https://preview.example.com',+ });+ expect(repeat.id).toBe(created.id);+ const versions = await workModel().listVersions(created.id);+ expect(versions.map((version) => version.changeType).sort()).toEqual(['created', 'updated']);+ });++ it('lets two workspace members register the same link', async () => {+ const workspaceId = 'work-agent-workspace-link';+ await serverDB.insert(workspaces).values({+ id: workspaceId,+ name: 'Test',+ primaryOwnerId: userId,+ slug: 'agent-work-link',+ });+ try {+ const link = { title: 'Docs', type: 'link', url: 'https://docs.example.com' } as const;+ const mine = await new WorkModel(serverDB, userId, workspaceId).createAgentWork(run, link);+ const theirs = await new WorkModel(serverDB, userId2, workspaceId).createAgentWork(+ { ...run, userId: userId2 },+ link,+ );++ expect(theirs.id).not.toBe(mine.id);+ expect(theirs.userId).toBe(userId2);+ } finally {+ await serverDB.delete(workspaces).where(eq(workspaces.id, workspaceId));+ }+ });++ it('refuses to delete a Work a goal node holds', async () => {+ const created = await workModel().createAgentWork(run, {+ title: 'Preview',+ type: 'link',+ url: 'https://preview.example.com',+ });+ const goal = await new GoalModel(serverDB, userId).create({+ subjectType: 'standalone',+ title: 'Ship the landing page',+ });+ const [node] = await serverDB+ .insert(goalNodes)+ .values({ goalId: goal.id, kind: 'task', title: 'Build preview' })+ .returning();+ const [version] = await workModel().listVersions(created.id);+ await serverDB+ .insert(goalNodeWorkVersions)+ .values({ nodeId: node.id, relation: 'produced', workVersionId: version.id });++ await expectAgentWorkError(workModel().deleteAgentWork(run, created.id), 'CONFLICT');+ expect(await serverDB.select().from(works).where(eq(works.id, created.id))).toHaveLength(1);+ });++ it("stamps a sub-agent run's versions with the root operation", async () => {+ const created = await workModel().createAgentWork(+ { ...run, operationId: 'op-child', rootOperationId: 'op-root' },+ { title: 'Preview', type: 'link', url: 'https://preview.example.com' },+ );++ const [version] = await workModel().listVersions(created.id);+ expect(version.rootOperationId).toBe('op-root');+ });++ it("keeps a teammate's agent Work out of reach in a workspace", async () => {+ const workspaceId = 'work-agent-workspace';+ await serverDB.insert(workspaces).values({+ id: workspaceId,+ name: 'Test',+ primaryOwnerId: userId,+ slug: 'agent-work',+ });+ try {+ const created = await new WorkModel(serverDB, userId, workspaceId).createAgentWork(run, {+ title: 'Preview',+ type: 'link',+ url: 'https://preview.example.com',+ });+ // A Work teammates can see, so only the creator check keeps it out of reach.+ await serverDB.update(works).set({ visibility: 'public' }).where(eq(works.id, created.id));++ await expectAgentWorkError(+ new WorkModel(serverDB, userId2, workspaceId).updateAgentWork(+ { ...run, userId: userId2 },+ { title: 'Hijacked', workId: created.id },+ ),+ 'NOT_FOUND',+ );+ } finally {+ await serverDB.delete(workspaces).where(eq(workspaces.id, workspaceId));+ }+ });++ it('stamps agentEditable on a task Work its tool config allows', async () => {+ const task = await new TaskModel(serverDB, userId).create({+ instruction: 'Write the plan',+ name: 'Plan',+ });+ const work = await workModel().registerTask({+ agentEditable: true,+ changeType: 'created',+ taskId: task.id,+ toolIdentifier: 'lobe-task',+ toolName: 'createTask',+ topicId,+ });++ expect(work).not.toBeNull();+ expect(await storedMetadata(work!.id)).toEqual({ agentEditable: true });++ // The card mirrors the task, so lh work update leaves its title to the task.+ await expectAgentWorkError(+ workModel().updateAgentWork(run, { title: 'Renamed', workId: work!.id }),+ 'BAD_REQUEST',+ );+ expect((await workModel().listVersions(work!.id)).length).toBe(1);+ });+});diff --git a/packages/database/src/models/work/__tests__/messageAttachment.test.ts b/packages/database/src/models/work/__tests__/messageAttachment.test.tsindex 520cd0f6760..cbd60af71d8 100644--- a/packages/database/src/models/work/__tests__/messageAttachment.test.ts+++ b/packages/database/src/models/work/__tests__/messageAttachment.test.ts@@ -64,6 +64,34 @@ describe('MessageModel · work summary attachment', () => {expect(result.find((m) => m.id === 'msg-tool')?.works).toBeUndefined();});+ it('gives an anchor whose Works were deleted an empty list, not an omitted one', async () => {+ const workModel = new WorkModel(serverDB, userId);+ const messageModel = new MessageModel(serverDB, userId);+ await serverDB.insert(messages).values({+ content: '',+ id: 'msg-anchor',+ metadata: { work: { rootOperationId: 'op-collection' } },+ role: 'assistant',+ topicId,+ userId,+ });+ const run = { operationId: 'op-collection', topicId, userId };+ const work = await workModel.createAgentWork(run, {+ title: 'Preview',+ type: 'link',+ url: 'https://preview.example.com',+ });+ expect(+ (await messageModel.query({ topicId })).find((m) => m.id === 'msg-anchor')?.works,+ ).toHaveLength(1);++ await workModel.deleteAgentWork(run, work.id);++ // Clients keep earlier works only when a payload omits them (skipWorks reads).+ const anchor = (await messageModel.query({ topicId })).find((m) => m.id === 'msg-anchor');+ expect(anchor?.works).toEqual([]);+ });+it('omits works for messages that carry no work rootOperationId', async () => {const messageModel = new MessageModel(serverDB, userId);diff --git a/packages/database/src/models/work/__tests__/queries.test.ts b/packages/database/src/models/work/__tests__/queries.test.tsindex afb8bde0c29..dfb557af430 100644--- a/packages/database/src/models/work/__tests__/queries.test.ts+++ b/packages/database/src/models/work/__tests__/queries.test.ts@@ -93,9 +93,9 @@ describe('WorkModel · queries', () => {rootOperationIds: ['op-batch-1', 'op-batch-2', 'op-batch-missing'],});- // One query per work type across all ids, not per (id x type). Five- // registered types now: canvas / document / external / file / task.- expect(selectSpy).toHaveBeenCalledTimes(5);+ // One query per work type across all ids, not per (id x type). Six+ // registered types now: canvas / document / external / file / collection / task.+ expect(selectSpy).toHaveBeenCalledTimes(6);expect(byOperations['op-batch-1']?.map((item) => item.resourceId)).toEqual([firstTask.id]);expect(byOperations['op-batch-2']?.map((item) => item.resourceId)).toEqual([secondTask.id]);expect(byOperations['op-batch-missing']).toEqual([]);diff --git a/packages/database/src/models/work/agentWork.ts b/packages/database/src/models/work/agentWork.tsnew file mode 100644index 00000000000..25499fb76a0--- /dev/null+++ b/packages/database/src/models/work/agentWork.ts@@ -0,0 +1,475 @@+import type {+ AgentWorkRunContext,+ CollectionWorkVersionMetadata,+ CreateAgentWorkInput,+ UpdateAgentWorkInput,+ WorkDisplayField,+ WorkItem,+ WorkVersionCumulativeUsage,+ WorkVersionMetadata,+} from '@lobechat/types';+import { AGENT_WORK_CLI_TOOL_IDENTIFIER, COLLECTION_WORK_MAX_ITEMS } from '@lobechat/types';+import { and, eq, exists, inArray, isNull } from 'drizzle-orm';++import { agentDeliveryWorks } from '../../schemas/agentDelivery';+import { goalNodeWorkVersions } from '../../schemas/goalGraph';+import { projectWorks } from '../../schemas/projectWork';+import { works, workVersions } from '../../schemas/work';+import { idGenerator } from '../../utils/idGenerator';+import { collectionCoverUrl } from './collection';+import { type WorkContext, workOwnership } from './context';+import { registerExternalWork } from './external';+import { fileBasename, fileWorkResourceId, registerFileWork } from './file';+import { sanitizeExternalUrl } from './toolResultParsing';+import { registerWorkVersion } from './writes';++export type AgentWorkErrorCode = 'BAD_REQUEST' | 'CONFLICT' | 'FORBIDDEN' | 'NOT_FOUND';++/** A refused agent Work write; `code` maps onto the transport's error code. */+export class AgentWorkError extends Error {+ constructor(+ readonly code: AgentWorkErrorCode,+ message: string,+ ) {+ super(message);+ this.name = 'AgentWorkError';+ }+}++/**+ * Hosts whose links are registered automatically under their own resource types+ * (GitHub issues/PRs, Linear issues/documents). Registering them again as a+ * plain `link` would show a second card for the same resource.+ */+const AUTO_REGISTERED_LINK_HOSTS = ['github.com', 'linear.app'];++const isAutoRegisteredHost = (hostname: string) =>+ AUTO_REGISTERED_LINK_HOSTS.some((host) => hostname === host || hostname.endsWith(`.${host}`));++/** Validate an agent-supplied link and return its canonical form (the `link` Work identity). */+const normalizeAgentLink = (value: string): string => {+ const safe = sanitizeExternalUrl(value);+ if (!safe) throw new AgentWorkError('BAD_REQUEST', 'Only http(s) links can be registered');++ const url = new URL(safe);+ if (isAutoRegisteredHost(url.hostname)) {+ throw new AgentWorkError(+ 'BAD_REQUEST',+ `${url.hostname} links are registered automatically when you create or edit them; do not register them yourself`,+ );+ }+ return url.href;+};++/**+ * Identity of an agent-registered link: the creator, the conversation and the+ * canonical URL, like {@link fileWorkResourceId}. Registering the same link+ * again in the same conversation adds a version; another conversation or+ * another workspace member gets a Work of their own. The card opens `url`,+ * never this id.+ */+export const linkWorkResourceId = (userId: string, topicId: string, url: string): string =>+ `${userId}:${topicId}:${url}`;++/** Tool names of the versions `createWork` / `updateWork` write. */+const AGENT_WORK_TOOL_NAMES = ['createWork', 'updateWork'];++const provenanceOf = (run: AgentWorkRunContext, toolName: string) => ({+ agentId: run.agentId ?? null,+ messageId: run.messageId ?? null,+ rootOperationId: run.rootOperationId ?? run.operationId,+ threadId: run.threadId ?? null,+ toolCallId: run.toolCallId ?? null,+ toolIdentifier: run.toolIdentifier ?? AGENT_WORK_CLI_TOOL_IDENTIFIER,+ toolName,+ topicId: run.topicId,+});++/**+ * Text limits of an agent-written Work, shared by `lh work` and the `lobe-work`+ * tool so a model cannot store unbounded text on a card or a share profile.+ */+const AGENT_WORK_TEXT_LIMITS = { caption: 500, description: 2000, title: 200 } as const;++const assertValidText = (input: {+ description?: string | null;+ items?: { caption?: string }[];+ title?: string;+}) => {+ if (input.title !== undefined && !input.title.trim()) {+ throw new AgentWorkError('BAD_REQUEST', 'A Work title cannot be empty');+ }+ if ((input.title?.length ?? 0) > AGENT_WORK_TEXT_LIMITS.title) {+ throw new AgentWorkError(+ 'BAD_REQUEST',+ `A Work title is at most ${AGENT_WORK_TEXT_LIMITS.title} characters`,+ );+ }+ if ((input.description?.length ?? 0) > AGENT_WORK_TEXT_LIMITS.description) {+ throw new AgentWorkError(+ 'BAD_REQUEST',+ `A Work description is at most ${AGENT_WORK_TEXT_LIMITS.description} characters`,+ );+ }+ if (input.items?.some((item) => (item.caption?.length ?? 0) > AGENT_WORK_TEXT_LIMITS.caption)) {+ throw new AgentWorkError(+ 'BAD_REQUEST',+ `An image caption is at most ${AGENT_WORK_TEXT_LIMITS.caption} characters`,+ );+ }+};++/** Check a collection's image list before it is stored as a version. */+const assertValidCollection = (collection: CollectionWorkVersionMetadata) => {+ if (collection.items.length === 0) {+ throw new AgentWorkError('BAD_REQUEST', 'A collection needs at least one image');+ }+ if (collection.items.length > COLLECTION_WORK_MAX_ITEMS) {+ throw new AgentWorkError(+ 'BAD_REQUEST',+ `A collection holds at most ${COLLECTION_WORK_MAX_ITEMS} images`,+ );+ }+ const fileIds = new Set(collection.items.map((item) => item.fileId));+ if (fileIds.size !== collection.items.length) {+ throw new AgentWorkError('BAD_REQUEST', 'Each image may appear in a collection only once');+ }+ if (collection.coverFileId && !fileIds.has(collection.coverFileId)) {+ throw new AgentWorkError('BAD_REQUEST', 'The cover must be one of the collection images');+ }+};++const collectionMetadata = (collection: CollectionWorkVersionMetadata): WorkVersionMetadata => ({+ collection: {+ ...(collection.coverFileId ? { coverFileId: collection.coverFileId } : {}),+ items: collection.items.map((item) => ({+ ...(item.caption ? { caption: item.caption } : {}),+ fileId: item.fileId,+ ...(item.mimeType ? { mimeType: item.mimeType } : {}),+ url: item.url,+ })),+ },+});++/**+ * Refuse to take over a Work the system collected automatically. Without this,+ * `lh work create` on a path the completion scan already registered would+ * append a version to a Work the agent may never update afterwards. Returns+ * whether the agent already created this Work, so a repeat create is labelled+ * as an update.+ */+const assertNotAutoRegistered = async (+ ctx: WorkContext,+ resourceType: 'file' | 'link',+ resourceId: string,+) => {+ const [existing] = await ctx.db+ .select({ metadata: works.metadata })+ .from(works)+ .where(+ and(+ workOwnership(ctx),+ eq(works.resourceType, resourceType),+ eq(works.resourceId, resourceId),+ ),+ )+ .limit(1);++ if (existing && existing.metadata?.agentEditable !== true) {+ throw new AgentWorkError(+ 'CONFLICT',+ 'This was already registered as a Work automatically and cannot be changed by the agent',+ );+ }+ return Boolean(existing);+};++/**+ * Register a Work the agent produced itself (`lh work create`). Creating the+ * same file path or link again in the same topic adds a version to the Work the+ * agent created before.+ */+export const createAgentWork = async (+ ctx: WorkContext,+ run: AgentWorkRunContext,+ input: CreateAgentWorkInput,+): Promise<WorkItem> => {+ assertValidText({+ description: input.description,+ items: input.type === 'collection' ? input.items : undefined,+ title: input.title,+ });+ if (input.type === 'file') {+ const { file } = input;+ await assertNotAutoRegistered(+ ctx,+ 'file',+ fileWorkResourceId(run.userId, run.topicId, file.filePath),+ );++ return registerFileWork(ctx, {+ ...provenanceOf(run, 'createWork'),+ agentEditable: true,+ description: input.description,+ filePath: file.filePath,+ metadata: {+ fileId: file.fileId,+ filePath: file.filePath,+ fileSize: file.fileSize,+ fileUrl: file.fileUrl,+ mimeType: file.mimeType,+ },+ title: input.title || fileBasename(file.filePath) || file.filePath,+ userId: run.userId,+ });+ }++ if (input.type === 'collection') {+ assertValidCollection(input);+ // Every create is a new collection: images are added to an existing one with+ // an update, which replaces its whole list.+ return registerWorkVersion(+ ctx,+ {+ resourceId: idGenerator('collections'),+ resourceType: 'collection',+ type: 'collection',+ userId: run.userId,+ visibility: 'private',+ },+ { ...provenanceOf(run, 'createWork'), agentEditable: true, changeType: 'created' },+ () => ({+ display: {+ description: input.description ?? null,+ title: input.title,+ url: collectionCoverUrl(input),+ },+ metadata: collectionMetadata(input),+ }),+ );+ }++ const url = normalizeAgentLink(input.url);+ const resourceId = linkWorkResourceId(run.userId, run.topicId, url);+ const alreadyCreated = await assertNotAutoRegistered(ctx, 'link', resourceId);++ const work = await registerExternalWork(ctx, {+ ...provenanceOf(run, 'createWork'),+ agentEditable: true,+ changeType: alreadyCreated ? 'updated' : 'created',+ description: input.description ?? null,+ resourceId,+ resourceType: 'link',+ title: input.title,+ url,+ });+ if (!work) throw new Error('Failed to register link Work');+ return work;+};++/** Work types an agent may change or delete after creating them. */+const isAgentManagedWork = (work: { resourceType: string; type: string }) =>+ work.type === 'file' ||+ work.type === 'collection' ||+ (work.type === 'external' && work.resourceType === 'link');++/**+ * Find a Work this run may change or delete: an `agentEditable` file, link or+ * collection Work of the same creator, produced in this run's conversation.+ */+const findAgentManagedWork = async (ctx: WorkContext, run: AgentWorkRunContext, workId: string) => {+ const [work] = await ctx.db+ .select()+ .from(works)+ .where(+ and(+ eq(works.id, workId),+ workOwnership(ctx),+ // Only the creator's runs in a conversation that produced the Work may+ // change it: workspace scope alone would let a teammate's run, or a run+ // in another conversation, append versions to it or delete it.+ eq(works.userId, run.userId),+ exists(+ ctx.db+ .select({ id: workVersions.id })+ .from(workVersions)+ .where(and(eq(workVersions.workId, works.id), eq(workVersions.topicId, run.topicId))),+ ),+ ),+ )+ .limit(1);+ if (!work?.resourceId) throw new AgentWorkError('NOT_FOUND', `Work ${workId} not found`);+ if (work.metadata?.agentEditable !== true) {+ throw new AgentWorkError(+ 'FORBIDDEN',+ 'This Work was registered automatically and cannot be changed by the agent',+ );+ }+ // A task or document card mirrors its own resource, so rewriting or removing+ // the card alone would leave it disagreeing with the task or document it+ // opens. `agentEditable` on those types stays a hook for future policy.+ if (!isAgentManagedWork(work)) {+ throw new AgentWorkError(+ 'BAD_REQUEST',+ 'Only file, link and collection Works can be changed this way; update the task or document itself',+ );+ }+ return { ...work, resourceId: work.resourceId };+};++/**+ * Add a version to a Work the agent created (`lh work update`, `lobe-work`+ * `updateWork`). Only Works stamped `agentEditable` at creation qualify;+ * fields left out keep their current values. A collection update replaces the+ * whole image list.+ */+export const updateAgentWork = async (+ ctx: WorkContext,+ run: AgentWorkRunContext,+ input: UpdateAgentWorkInput,+): Promise<WorkItem> => {+ const work = await findAgentManagedWork(ctx, run, input.workId);++ if (input.file && work.type !== 'file') {+ throw new AgentWorkError('BAD_REQUEST', 'Only a file Work takes a new file');+ }+ if (input.collection && work.type !== 'collection') {+ throw new AgentWorkError('BAD_REQUEST', 'Only a collection Work takes images');+ }+ if (input.collection) assertValidCollection(input.collection);+ assertValidText({+ description: input.description,+ items: input.collection?.items,+ title: input.title,+ });++ const patchFields: WorkDisplayField[] = [];+ if (input.title !== undefined) patchFields.push('title');+ if (input.description !== undefined) patchFields.push('description');+ if (input.file || input.collection) patchFields.push('url');+ if (patchFields.length === 0) {+ throw new AgentWorkError('BAD_REQUEST', 'Nothing to update');+ }++ let metadata: WorkVersionMetadata | undefined;+ if (input.file) {+ metadata = {+ fileId: input.file.fileId,+ fileSize: input.file.fileSize,+ fileUrl: input.file.fileUrl,+ mimeType: input.file.mimeType,+ };+ } else if (input.collection) {+ metadata = collectionMetadata(input.collection);+ }++ return registerWorkVersion(+ ctx,+ {+ resourceId: work.resourceId,+ resourceType: work.resourceType,+ type: work.type,+ userId: work.userId,+ visibility: work.visibility,+ },+ { ...provenanceOf(run, 'updateWork'), changeType: 'updated' },+ () => ({+ display: {+ description: input.description,+ title: input.title,+ url:+ input.file?.fileUrl ??+ (input.collection ? collectionCoverUrl(input.collection) : undefined),+ },+ metadata,+ // A file- or image-only update patches `url`, so it records a version+ // even when the title and description are unchanged.+ patchFields,+ }),+ );+};++/**+ * Whether a goal node, delivery or project holds this Work. Their links cascade+ * from the Work, so deleting it would silently drop the evidence a goal node+ * pinned, a delivery shipped or a project collected.+ */+const isWorkReferenced = async (ctx: WorkContext, workId: string): Promise<boolean> => {+ const [goalNode, delivery, project] = await Promise.all([+ ctx.db+ .select({ id: goalNodeWorkVersions.id })+ .from(goalNodeWorkVersions)+ .innerJoin(workVersions, eq(workVersions.id, goalNodeWorkVersions.workVersionId))+ .where(eq(workVersions.workId, workId))+ .limit(1),+ ctx.db+ .select({ id: agentDeliveryWorks.id })+ .from(agentDeliveryWorks)+ .where(eq(agentDeliveryWorks.workId, workId))+ .limit(1),+ ctx.db+ .select({ id: projectWorks.id })+ .from(projectWorks)+ .where(eq(projectWorks.workId, workId))+ .limit(1),+ ]);+ return goalNode.length > 0 || delivery.length > 0 || project.length > 0;+};++/**+ * Delete a Work the agent created by mistake (`lh work delete`, `lobe-work`+ * `deleteWork`). Removes the card and its versions; the files it points at+ * stay in the file store. A Work a goal node, delivery or project already holds+ * is refused: update it instead.+ */+export const deleteAgentWork = async (+ ctx: WorkContext,+ run: AgentWorkRunContext,+ workId: string,+): Promise<{ id: string; title: string | null }> => {+ const work = await findAgentManagedWork(ctx, run, workId);+ if (await isWorkReferenced(ctx, work.id)) {+ throw new AgentWorkError(+ 'CONFLICT',+ 'This Work is part of a goal, delivery or project and cannot be deleted; update it instead',+ );+ }+ // Versions go with the Work through the `work_versions.work_id` cascade.+ await ctx.db.delete(works).where(and(eq(works.id, work.id), eq(works.userId, run.userId)));+ return { id: work.id, title: work.title };+};++/**+ * Give the run's agent-written Work versions the run's spend. `createWork` /+ * `updateWork` write their version while the tool call runs, because the agent+ * needs the Work id in the result, so the tool call's cost is not known yet and+ * the version lands without one. Run completion calls this with the run total,+ * the same figure the Works scanned at completion carry. Versions that already+ * have a cost are left alone, so a retried completion changes nothing.+ */+export const fillAgentWorkCost = async (+ ctx: WorkContext,+ params: {+ cumulativeCost: number | null;+ cumulativeUsage: WorkVersionCumulativeUsage | null;+ rootOperationId: string;+ },+): Promise<number> => {+ if (params.cumulativeCost === null) return 0;+ const updated = await ctx.db+ .update(workVersions)+ .set({ cumulativeCost: params.cumulativeCost, cumulativeUsage: params.cumulativeUsage })+ .where(+ and(+ eq(workVersions.rootOperationId, params.rootOperationId),+ isNull(workVersions.cumulativeCost),+ inArray(workVersions.toolName, AGENT_WORK_TOOL_NAMES),+ inArray(+ workVersions.workId,+ ctx.db.select({ id: works.id }).from(works).where(workOwnership(ctx)),+ ),+ ),+ )+ .returning({ id: workVersions.id });+ return updated.length;+};diff --git a/packages/database/src/models/work/collection.ts b/packages/database/src/models/work/collection.tsnew file mode 100644index 00000000000..d242d91f63e--- /dev/null+++ b/packages/database/src/models/work/collection.ts@@ -0,0 +1,17 @@+import type { CollectionWorkVersionMetadata } from '@lobechat/types';++import { createDisplayWorkAdapter } from './displayWork';++export const collectionWorkAdapter = createDisplayWorkAdapter({ type: 'collection' });++/**+ * The image a collection card shows: the named cover, else the first image. List+ * rows carry no version metadata, so its URL is also denormalized into+ * `works.url`.+ */+export const collectionCoverUrl = (collection: CollectionWorkVersionMetadata): string | null => {+ const cover = collection.coverFileId+ ? collection.items.find((item) => item.fileId === collection.coverFileId)+ : undefined;+ return (cover ?? collection.items[0])?.url ?? null;+};diff --git a/packages/database/src/models/work/file.ts b/packages/database/src/models/work/file.tsindex d4b66c5c068..2ae1cd4023d 100644--- a/packages/database/src/models/work/file.ts+++ b/packages/database/src/models/work/file.ts@@ -36,7 +36,7 @@ export const fileWorkResourceId = (userId: string, topicId: string, filePath: st* builtin-tools `getBasename` without pulling that package into the DB layer —* used to denormalize the `identifier` display column (see {@link registerFileWork}).*/-const fileBasename = (filePath: string): string =>+export const fileBasename = (filePath: string): string =>filePath.replaceAll('\\', '/').split('/').findLast(Boolean)?.trim() ?? '';/**@@ -116,6 +116,7 @@ export const registerFileWork = async (visibility: params.visibility ?? 'private',},{+ agentEditable: params.agentEditable,agentId: params.agentId,changeType,cumulativeCost: params.cumulativeCost,@@ -138,7 +139,7 @@ export const registerFileWork = async (// sidebar's fallback label renders the filename instead of leaking the// internal `resourceId` (`userId:topicId:filePath`).display: {- description: params.filePath,+ description: params.description || params.filePath,identifier: fileBasename(params.filePath) || null,title: params.title,url: params.metadata.fileUrl ?? null,diff --git a/packages/database/src/models/work/index.ts b/packages/database/src/models/work/index.tsindex e3fdf38f092..a110574f733 100644--- a/packages/database/src/models/work/index.ts+++ b/packages/database/src/models/work/index.ts@@ -1,6 +1,8 @@import {type ArtboardWorkPublishMetadata,+ type AgentWorkRunContext,type CanvasWorkPublishMetadata,+ type CreateAgentWorkInput,type DeleteDocumentWorkParams,type DeleteTaskWorkParams,type DeleteWorkParams,@@ -13,6 +15,7 @@ import {type RegisterSkillToolResultWorkParams,type RegisterTaskWorkParams,type SkillToolResultWorkInput,+ type UpdateAgentWorkInput,type WorkAccessScope,type WorkItem,type WorkSkillProvider,@@ -22,6 +25,7 @@ import debug from 'debug';import type { LobeChatDatabase } from '../../type';import { ScmChangeRequestModel } from '../scm';+import { createAgentWork, deleteAgentWork, fillAgentWorkCost, updateAgentWork } from './agentWork';import {clearArtboardPublish,findArtboardIdsByDeploymentIds,@@ -87,6 +91,7 @@ const log = debug('lobe-database:work-model');* module, keeping the polymorphic Work registry logic split by provider type* without changing the public API surface.*/+export { AgentWorkError, type AgentWorkErrorCode } from './agentWork';export type { GithubShellNormalizeOptions } from './githubToolResult';export { type GitPushResult, parseGithubRemoteUrl, parseGitPushResult } from './gitPushResult';@@ -201,6 +206,22 @@ export class WorkModel {userId: string;}): Promise<{ id: string } | null> => findFileWorkVersionByToolCall(this.ctx, params);+ /** `lh work create` / `lobe-work`: register a file, link or collection the agent produced. See {@link createAgentWork}. */+ createAgentWork = (run: AgentWorkRunContext, input: CreateAgentWorkInput) =>+ createAgentWork(this.ctx, run, input);++ /** `lh work update`: add a version to an agent-created Work. See {@link updateAgentWork}. */+ updateAgentWork = (run: AgentWorkRunContext, input: UpdateAgentWorkInput) =>+ updateAgentWork(this.ctx, run, input);++ /** `lh work delete`: remove a Work the agent created by mistake. See {@link deleteAgentWork}. */+ deleteAgentWork = (run: AgentWorkRunContext, workId: string) =>+ deleteAgentWork(this.ctx, run, workId);++ /** Run completion: give the run's agent-written versions its spend. See {@link fillAgentWorkCost}. */+ fillAgentWorkCost = (params: Parameters<typeof fillAgentWorkCost>[1]) =>+ fillAgentWorkCost(this.ctx, params);+handleSkillToolResult = async (params: RegisterSkillToolResultWorkParams,): Promise<WorkItem | null> => {diff --git a/packages/database/src/models/work/internal.ts b/packages/database/src/models/work/internal.tsindex e4192fa6ad3..24b2c523bb6 100644--- a/packages/database/src/models/work/internal.ts+++ b/packages/database/src/models/work/internal.ts@@ -67,6 +67,7 @@ export const truncateSummaryText = (value: string | null | undefined): string |/** Provenance fields shared by all four Register*WorkParams shapes. */export type WorkVersionEventParams = Pick<RegisterTaskWorkParams,+ | 'agentEditable'| 'agentId'| 'cumulativeCost'| 'cumulativeUsage'@@ -187,7 +188,7 @@ export interface TaskWorkSummaryQueryRow {* Work types whose list rows are fully described by the `works` display columns* (unlike `task`, which additionally joins the live tasks table).*/-export type DisplayWorkType = 'artboard' | 'canvas' | 'document' | 'external' | 'file';+export type DisplayWorkType = 'artboard' | 'canvas' | 'document' | 'external' | 'file' | 'collection';/** Version-event row for display-backed types (each mutation event). */export interface DisplayVersionEventRow {diff --git a/packages/database/src/models/work/registry.ts b/packages/database/src/models/work/registry.tsindex 0ab4eed34e3..1cd0371036c 100644--- a/packages/database/src/models/work/registry.ts+++ b/packages/database/src/models/work/registry.ts@@ -2,6 +2,7 @@ import type { WorkType } from '@lobechat/types';import { artboardWorkAdapter } from './artboard';import { canvasWorkAdapter } from './canvas';+import { collectionWorkAdapter } from './collection';import { documentWorkAdapter } from './document';import { externalWorkAdapter } from './external';import { fileWorkAdapter } from './file';@@ -21,6 +22,7 @@ export const WORK_TYPE_ADAPTERS = {document: documentWorkAdapter,external: externalWorkAdapter,file: fileWorkAdapter,+ collection: collectionWorkAdapter,goal_report: goalReportWorkAdapter,task: taskWorkAdapter,} satisfies Record<WorkType, WorkTypeAdapter>;@@ -45,7 +47,7 @@ export const workTypeAdapters = WORK_TYPES.map(* request that does not opt in therefore receives the pre-`file` set, keeping* every already-deployed client byte-identically safe; new clients opt in.*/-const OPT_IN_WORK_TYPES = new Set<WorkType>(['canvas', 'file']);+const OPT_IN_WORK_TYPES = new Set<WorkType>(['canvas', 'file', 'collection']);/*** `artboard` shipped after clients already sent `includeFileWorks`, so it needsdiff --git a/packages/database/src/models/work/writes.ts b/packages/database/src/models/work/writes.tsindex a8be6df8b84..ddf5bceb32f 100644--- a/packages/database/src/models/work/writes.ts+++ b/packages/database/src/models/work/writes.ts@@ -141,17 +141,23 @@ const buildVersionMetadata = (* `buildInput` receives.*//** Server-owned `works.metadata` for a fresh identity row under `ctx`'s scope. */-const buildWorkMetadata = (ctx: WorkContext): WorkMetadata | null => {+const buildWorkMetadata = (+ ctx: WorkContext,+ params: Pick<WorkVersionEventParams, 'agentEditable'>,+): WorkMetadata | null => {const scope = resolveWorkAccessScope(ctx);- if (scope.type !== 'agentShare') return null;-- return {- agentShare: {- shareId: scope.shareId,- topicId: scope.topicId,- visitorUserId: scope.visitorUserId,- },+ const metadata: WorkMetadata = {+ ...(params.agentEditable && { agentEditable: true }),+ ...(scope.type === 'agentShare' && {+ agentShare: {+ shareId: scope.shareId,+ topicId: scope.topicId,+ visitorUserId: scope.visitorUserId,+ },+ }),};++ return Object.keys(metadata).length > 0 ? metadata : null;};export const registerWorkVersion = async (@@ -176,7 +182,9 @@ export const registerWorkVersion = async (// from a visitor's share topic carries that topic's scope for its// whole life, so the creator's ordinary reads (and any other// visitor topic) never resolve it — see `workMatchesAccessScope`.- metadata: buildWorkMetadata(ctx),+ // `agentEditable` follows the same rule: a Work's editability by+ // the agent is fixed by whoever registered it first.+ metadata: buildWorkMetadata(ctx, params),// Origin provenance is stamped ONLY here: it records where the Work// identity was first registered and stays immutable through every// later version (the current-projection UPDATE below never touches it).diff --git a/packages/database/src/utils/idGenerator.ts b/packages/database/src/utils/idGenerator.tsindex 6d9564ed5f2..ea42315710e 100644--- a/packages/database/src/utils/idGenerator.ts+++ b/packages/database/src/utils/idGenerator.ts@@ -29,6 +29,7 @@ const prefixes = {evalTestCases: 'case',expertiseDomains: 'epd',files: 'file',+ collections: 'col',generationBatches: 'gb',generationTopics: 'gt',generations: 'gen',diff --git a/packages/locales/src/default/agent.ts b/packages/locales/src/default/agent.tsindex 5b3c281c937..42c6c3c0491 100644--- a/packages/locales/src/default/agent.ts+++ b/packages/locales/src/default/agent.ts@@ -1277,6 +1277,10 @@ export default {'share.visitor.profile.works.type.document': 'Document','share.visitor.profile.works.type.task': 'Task','share.visitor.profile.works.type.file': 'File',+ 'share.visitor.profile.works.images_one': '{{count}} image',+ 'share.visitor.profile.works.images_other': '{{count}} images',+ 'share.visitor.profile.works.type.collection': 'Gallery',+ 'share.visitor.profile.works.viewImages': 'View images','share.visitor.profile.works.type.external': 'Linked work','share.settings.profile.title': 'Public profile','share.settings.profile.desc':diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex 1439b4a8703..4512e281060 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -4168,6 +4168,10 @@ export default {'workingPanel.works.documentLoadError': 'Failed to load document','workingPanel.works.canvasShared': 'Shared','workingPanel.works.canvasUntitled': 'Untitled canvas',+ 'workingPanel.works.collectionCount_one': '{{count}} image',+ 'workingPanel.works.collectionCount_other': '{{count}} images',+ 'workingPanel.works.collectionEmpty': 'This gallery has no images',+ 'workingPanel.works.collectionUntitled': 'Untitled gallery','workingPanel.works.changeType.created': 'Created','workingPanel.works.changeType.updated': 'Updated','workingPanel.works.documentDeleted': 'This document has been deleted',diff --git a/packages/locales/src/default/file.ts b/packages/locales/src/default/file.tsindex 4e434c629ca..9cd47b2de17 100644--- a/packages/locales/src/default/file.ts+++ b/packages/locales/src/default/file.ts@@ -607,10 +607,12 @@ export default {'work.type.canvas': 'Canvas','work.type.document': 'Document','work.type.file': 'File',+ 'work.type.collection': 'Gallery','work.type.githubIssue': 'GitHub Issue','work.type.githubPullRequest': 'GitHub PR','work.type.linearDocument': 'Linear Document','work.type.linearIssue': 'Linear Issue',+ 'work.type.link': 'Link','work.type.task': 'Task','work.updatedAt': 'Updated {{date}}','work.topicGroup.other': 'Other',diff --git a/packages/locales/src/default/plugin.ts b/packages/locales/src/default/plugin.tsindex 45c378f424d..649211ea3cc 100644--- a/packages/locales/src/default/plugin.ts+++ b/packages/locales/src/default/plugin.ts@@ -105,6 +105,13 @@ export default {'Checked moments ago. Wait 30 seconds, then check again','builtins.lobe-mcp-events.error.unknown': "The subscription request didn't finish",'builtins.lobe-webhook.title': 'Webhooks',+ 'builtins.lobe-work.title': 'Works',+ 'builtins.lobe-work.apiName.createWork': 'Create Work',+ 'builtins.lobe-work.apiName.updateWork': 'Update Work',+ 'builtins.lobe-work.apiName.deleteWork': 'Delete Work',+ 'builtins.lobe-work.inspector.failed': 'Failed',+ 'builtins.lobe-work.inspector.images_one': '{{count}} image',+ 'builtins.lobe-work.inspector.images_other': '{{count}} images','builtins.lobe-webhook.apiName.listWebhooks': "List this agent's webhooks",'builtins.lobe-webhook.apiName.createWebhook': 'Create webhook','builtins.lobe-webhook.apiName.updateWebhook': 'Update webhook',diff --git a/packages/openapi/openapi.yml b/packages/openapi/openapi.ymlindex 5c54726f1cf..6f92a03245e 100644--- a/packages/openapi/openapi.yml+++ b/packages/openapi/openapi.yml@@ -3469,7 +3469,9 @@ components:- github_pull_request- linear_document- linear_issue+ - link- file+ - collection- goal_report- taskstatus:@@ -3488,6 +3490,7 @@ components:- document- external- file+ - collection- goal_report- taskurl:diff --git a/packages/openapi/src/types/goal.type.ts b/packages/openapi/src/types/goal.type.tsindex b101aff9fa0..354eb91eb4b 100644--- a/packages/openapi/src/types/goal.type.ts+++ b/packages/openapi/src/types/goal.type.ts@@ -238,6 +238,7 @@ const WorkTypeSchema = unionEnum<WorkType>()(['document','external','file',+ 'collection','goal_report','task',]);@@ -249,7 +250,9 @@ const WorkResourceTypeSchema = unionEnum<WorkResourceType>()(['github_pull_request','linear_document','linear_issue',+ 'link','file',+ 'collection','goal_report','task',]);diff --git a/packages/sdk/src/generated/index.ts b/packages/sdk/src/generated/index.tsindex 9ef48128936..a3e29eb7758 100644--- a/packages/sdk/src/generated/index.ts+++ b/packages/sdk/src/generated/index.ts@@ -1,4 +1,4 @@// This file is auto-generated by @hey-api/openapi-ts-export { AgentGroups, Agents, ApiKeys, Audio, Chat, ChatGroups, Eval, Files, Goals, Health, Im, KnowledgeBases, LobeHub, McpServers, Memories, Messages, MessageTranslations, Models, Notifications, type Options, Permissions, Plugins, Providers, PushTokens, Responses, Roles, Signals, Tasks, Topics, Usage as Usage2, Users } from './sdk.gen';-export type { Agent, AgentAccount, AgentAccountCapabilities, AgentAccountList, AgentDetail, AgentFile, AgentGroup, AgentKnowledgeBase, AgentList, AgentPlugin, AgentSignalEmission, AgentSignalReceipt, AgentSignalReceiptList, ApiError, ApiErrorCode, ApiKey, AsyncTaskError, BatchFileUploadResult, BatchGetFilesResult, ChatGenerateReplyResponse, ChatGroup, ChatGroupList, ChatGroupMember, ChatResponse, ChatTranslateResponse, ClientOptions, CreatedAgentGroup, CreatedApiKey, DeleteApiV1AgentGroupsByIdData, DeleteApiV1AgentGroupsByIdError, DeleteApiV1AgentGroupsByIdErrors, DeleteApiV1AgentGroupsByIdResponse, DeleteApiV1AgentGroupsByIdResponses, DeleteApiV1AgentsByIdAccountsByAccountIdData, DeleteApiV1AgentsByIdAccountsByAccountIdError, DeleteApiV1AgentsByIdAccountsByAccountIdErrors, DeleteApiV1AgentsByIdAccountsByAccountIdResponse, DeleteApiV1AgentsByIdAccountsByAccountIdResponses, DeleteApiV1AgentsByIdData, DeleteApiV1AgentsByIdError, DeleteApiV1AgentsByIdErrors, DeleteApiV1AgentsByIdResponse, DeleteApiV1AgentsByIdResponses, DeleteApiV1ApiKeysByIdData, DeleteApiV1ApiKeysByIdError, DeleteApiV1ApiKeysByIdErrors, DeleteApiV1ApiKeysByIdResponse, DeleteApiV1ApiKeysByIdResponses, DeleteApiV1ChatGroupsByIdData, DeleteApiV1ChatGroupsByIdError, DeleteApiV1ChatGroupsByIdErrors, DeleteApiV1ChatGroupsByIdMembersData, DeleteApiV1ChatGroupsByIdMembersError, DeleteApiV1ChatGroupsByIdMembersErrors, DeleteApiV1ChatGroupsByIdMembersResponse, DeleteApiV1ChatGroupsByIdMembersResponses, DeleteApiV1ChatGroupsByIdResponse, DeleteApiV1ChatGroupsByIdResponses, DeleteApiV1EvalBenchmarksByIdData, DeleteApiV1EvalBenchmarksByIdError, DeleteApiV1EvalBenchmarksByIdErrors, DeleteApiV1EvalBenchmarksByIdResponse, DeleteApiV1EvalBenchmarksByIdResponses, DeleteApiV1EvalDatasetsByIdData, DeleteApiV1EvalDatasetsByIdError, DeleteApiV1EvalDatasetsByIdErrors, DeleteApiV1EvalDatasetsByIdResponse, DeleteApiV1EvalDatasetsByIdResponses, DeleteApiV1EvalTestCasesByIdData, DeleteApiV1EvalTestCasesByIdError, DeleteApiV1EvalTestCasesByIdErrors, DeleteApiV1EvalTestCasesByIdResponse, DeleteApiV1EvalTestCasesByIdResponses, DeleteApiV1FilesByIdData, DeleteApiV1FilesByIdError, DeleteApiV1FilesByIdErrors, DeleteApiV1FilesByIdResponse, DeleteApiV1FilesByIdResponses, DeleteApiV1GoalsByIdData, DeleteApiV1GoalsByIdError, DeleteApiV1GoalsByIdErrors, DeleteApiV1GoalsByIdResponse, DeleteApiV1GoalsByIdResponses, DeleteApiV1KnowledgeBasesByIdData, DeleteApiV1KnowledgeBasesByIdError, DeleteApiV1KnowledgeBasesByIdErrors, DeleteApiV1KnowledgeBasesByIdFilesBatchData, DeleteApiV1KnowledgeBasesByIdFilesBatchError, DeleteApiV1KnowledgeBasesByIdFilesBatchErrors, DeleteApiV1KnowledgeBasesByIdFilesBatchResponse, DeleteApiV1KnowledgeBasesByIdFilesBatchResponses, DeleteApiV1KnowledgeBasesByIdResponse, DeleteApiV1KnowledgeBasesByIdResponses, DeleteApiV1McpServersByIdData, DeleteApiV1McpServersByIdError, DeleteApiV1McpServersByIdErrors, DeleteApiV1McpServersByIdResponse, DeleteApiV1McpServersByIdResponses, DeleteApiV1MemoriesByCategoryByIdData, DeleteApiV1MemoriesByCategoryByIdError, DeleteApiV1MemoriesByCategoryByIdErrors, DeleteApiV1MemoriesByCategoryByIdResponse, DeleteApiV1MemoriesByCategoryByIdResponses, DeleteApiV1MemoriesData, DeleteApiV1MemoriesError, DeleteApiV1MemoriesErrors, DeleteApiV1MemoriesResponse, DeleteApiV1MemoriesResponses, DeleteApiV1MessagesByIdData, DeleteApiV1MessagesByIdError, DeleteApiV1MessagesByIdErrors, DeleteApiV1MessagesByIdResponse, DeleteApiV1MessagesByIdResponses, DeleteApiV1MessagesData, DeleteApiV1MessagesError, DeleteApiV1MessagesErrors, DeleteApiV1MessagesResponse, DeleteApiV1MessagesResponses, DeleteApiV1MessageTranslationsByMessageIdData, DeleteApiV1MessageTranslationsByMessageIdError, DeleteApiV1MessageTranslationsByMessageIdErrors, DeleteApiV1MessageTranslationsByMessageIdResponse, DeleteApiV1MessageTranslationsByMessageIdResponses, DeleteApiV1PermissionsByIdData, DeleteApiV1PermissionsByIdError, DeleteApiV1PermissionsByIdErrors, DeleteApiV1PermissionsByIdResponse, DeleteApiV1PermissionsByIdResponses, DeleteApiV1ProvidersByIdData, DeleteApiV1ProvidersByIdError, DeleteApiV1ProvidersByIdErrors, DeleteApiV1ProvidersByIdResponse, DeleteApiV1ProvidersByIdResponses, DeleteApiV1PushTokensByDeviceIdData, DeleteApiV1PushTokensByDeviceIdError, DeleteApiV1PushTokensByDeviceIdErrors, DeleteApiV1PushTokensByDeviceIdResponse, DeleteApiV1PushTokensByDeviceIdResponses, DeleteApiV1RolesByIdData, DeleteApiV1RolesByIdError, DeleteApiV1RolesByIdErrors, DeleteApiV1RolesByIdPermissionsData, DeleteApiV1RolesByIdPermissionsError, DeleteApiV1RolesByIdPermissionsErrors, DeleteApiV1RolesByIdPermissionsResponse, DeleteApiV1RolesByIdPermissionsResponses, DeleteApiV1RolesByIdResponse, DeleteApiV1RolesByIdResponses, DeleteApiV1TasksByIdData, DeleteApiV1TasksByIdError, DeleteApiV1TasksByIdErrors, DeleteApiV1TasksByIdResponse, DeleteApiV1TasksByIdResponses, DeleteApiV1TopicsByIdData, DeleteApiV1TopicsByIdError, DeleteApiV1TopicsByIdErrors, DeleteApiV1TopicsByIdResponse, DeleteApiV1TopicsByIdResponses, DeleteApiV1UsersByIdData, DeleteApiV1UsersByIdError, DeleteApiV1UsersByIdErrors, DeleteApiV1UsersByIdResponse, DeleteApiV1UsersByIdResponses, DeleteApiV1UsersByIdRolesData, DeleteApiV1UsersByIdRolesError, DeleteApiV1UsersByIdRolesErrors, DeleteApiV1UsersByIdRolesResponse, DeleteApiV1UsersByIdRolesResponses, DeletedResource, DeletedResources, EvalBatchReportResult, EvalBenchmark, EvalBenchmarkRubric, EvalCaseResult, EvalDataset, EvalReportReceipt, EvalReportResult, EvalRetryErrors, EvalRubricScore, EvalRun, EvalRunMetrics, EvalRunResult, EvalRunTopic, EvalStoredResult, EvalTestCase, EvalThreadResult, File, FileAsyncTask, FileChunkStatus, FileChunkTask, FileDetail, FileKnowledgeBaseRef, FileList, FileListItem, FileParseResult, FileUrl, FileUser, GetApiV1AgentGroupsByIdData, GetApiV1AgentGroupsByIdError, GetApiV1AgentGroupsByIdErrors, GetApiV1AgentGroupsByIdResponse, GetApiV1AgentGroupsByIdResponses, GetApiV1AgentGroupsData, GetApiV1AgentGroupsError, GetApiV1AgentGroupsErrors, GetApiV1AgentGroupsResponse, GetApiV1AgentGroupsResponses, GetApiV1AgentsByIdAccountsByAccountIdData, GetApiV1AgentsByIdAccountsByAccountIdError, GetApiV1AgentsByIdAccountsByAccountIdErrors, GetApiV1AgentsByIdAccountsByAccountIdResponse, GetApiV1AgentsByIdAccountsByAccountIdResponses, GetApiV1AgentsByIdAccountsData, GetApiV1AgentsByIdAccountsError, GetApiV1AgentsByIdAccountsErrors, GetApiV1AgentsByIdAccountsResponse, GetApiV1AgentsByIdAccountsResponses, GetApiV1AgentsByIdData, GetApiV1AgentsByIdError, GetApiV1AgentsByIdErrors, GetApiV1AgentsByIdResponse, GetApiV1AgentsByIdResponses, GetApiV1AgentsData, GetApiV1AgentsError, GetApiV1AgentsErrors, GetApiV1AgentsResponse, GetApiV1AgentsResponses, GetApiV1ApiKeysByIdData, GetApiV1ApiKeysByIdError, GetApiV1ApiKeysByIdErrors, GetApiV1ApiKeysByIdResponse, GetApiV1ApiKeysByIdResponses, GetApiV1ApiKeysData, GetApiV1ApiKeysError, GetApiV1ApiKeysErrors, GetApiV1ApiKeysResponse, GetApiV1ApiKeysResponses, GetApiV1ChatGroupsByIdData, GetApiV1ChatGroupsByIdError, GetApiV1ChatGroupsByIdErrors, GetApiV1ChatGroupsByIdResponse, GetApiV1ChatGroupsByIdResponses, GetApiV1ChatGroupsData, GetApiV1ChatGroupsError, GetApiV1ChatGroupsErrors, GetApiV1ChatGroupsResponse, GetApiV1ChatGroupsResponses, GetApiV1EvalBenchmarksByIdData, GetApiV1EvalBenchmarksByIdError, GetApiV1EvalBenchmarksByIdErrors, GetApiV1EvalBenchmarksByIdResponse, GetApiV1EvalBenchmarksByIdResponses, GetApiV1EvalBenchmarksData, GetApiV1EvalBenchmarksError, GetApiV1EvalBenchmarksErrors, GetApiV1EvalBenchmarksResponse, GetApiV1EvalBenchmarksResponses, GetApiV1EvalDatasetsByDatasetIdTestCasesData, GetApiV1EvalDatasetsByDatasetIdTestCasesError, GetApiV1EvalDatasetsByDatasetIdTestCasesErrors, GetApiV1EvalDatasetsByDatasetIdTestCasesResponse, GetApiV1EvalDatasetsByDatasetIdTestCasesResponses, GetApiV1EvalDatasetsByIdData, GetApiV1EvalDatasetsByIdError, GetApiV1EvalDatasetsByIdErrors, GetApiV1EvalDatasetsByIdResponse, GetApiV1EvalDatasetsByIdResponses, GetApiV1EvalDatasetsData, GetApiV1EvalDatasetsError, GetApiV1EvalDatasetsErrors, GetApiV1EvalDatasetsResponse, GetApiV1EvalDatasetsResponses, GetApiV1EvalRunsByIdData, GetApiV1EvalRunsByIdError, GetApiV1EvalRunsByIdErrors, GetApiV1EvalRunsByIdResponse, GetApiV1EvalRunsByIdResponses, GetApiV1EvalRunsByIdResultsData, GetApiV1EvalRunsByIdResultsError, GetApiV1EvalRunsByIdResultsErrors, GetApiV1EvalRunsByIdResultsResponse, GetApiV1EvalRunsByIdResultsResponses, GetApiV1EvalRunsByIdTopicsData, GetApiV1EvalRunsByIdTopicsError, GetApiV1EvalRunsByIdTopicsErrors, GetApiV1EvalRunsByIdTopicsResponse, GetApiV1EvalRunsByIdTopicsResponses, GetApiV1EvalRunsData, GetApiV1EvalRunsError, GetApiV1EvalRunsErrors, GetApiV1EvalRunsResponse, GetApiV1EvalRunsResponses, GetApiV1EvalTestCasesByIdData, GetApiV1EvalTestCasesByIdError, GetApiV1EvalTestCasesByIdErrors, GetApiV1EvalTestCasesByIdResponse, GetApiV1EvalTestCasesByIdResponses, GetApiV1FilesByIdChunksData, GetApiV1FilesByIdChunksError, GetApiV1FilesByIdChunksErrors, GetApiV1FilesByIdChunksResponse, GetApiV1FilesByIdChunksResponses, GetApiV1FilesByIdData, GetApiV1FilesByIdError, GetApiV1FilesByIdErrors, GetApiV1FilesByIdResponse, GetApiV1FilesByIdResponses, GetApiV1FilesByIdUrlData, GetApiV1FilesByIdUrlError, GetApiV1FilesByIdUrlErrors, GetApiV1FilesByIdUrlResponse, GetApiV1FilesByIdUrlResponses, GetApiV1FilesData, GetApiV1FilesError, GetApiV1FilesErrors, GetApiV1FilesResponse, GetApiV1FilesResponses, GetApiV1GoalsByIdData, GetApiV1GoalsByIdError, GetApiV1GoalsByIdErrors, GetApiV1GoalsByIdResponse, GetApiV1GoalsByIdResponses, GetApiV1GoalsByIdSupervisionData, GetApiV1GoalsByIdSupervisionError, GetApiV1GoalsByIdSupervisionErrors, GetApiV1GoalsByIdSupervisionResponse, GetApiV1GoalsByIdSupervisionResponses, GetApiV1GoalsData, GetApiV1GoalsError, GetApiV1GoalsErrors, GetApiV1GoalsResponse, GetApiV1GoalsResponses, GetApiV1HealthData, GetApiV1HealthResponse, GetApiV1HealthResponses, GetApiV1ImTopicsByTopicIdSyncData, GetApiV1ImTopicsByTopicIdSyncError, GetApiV1ImTopicsByTopicIdSyncErrors, GetApiV1ImTopicsByTopicIdSyncResponse, GetApiV1ImTopicsByTopicIdSyncResponses, GetApiV1KnowledgeBasesByIdData, GetApiV1KnowledgeBasesByIdError, GetApiV1KnowledgeBasesByIdErrors, GetApiV1KnowledgeBasesByIdFilesData, GetApiV1KnowledgeBasesByIdFilesError, GetApiV1KnowledgeBasesByIdFilesErrors, GetApiV1KnowledgeBasesByIdFilesResponse, GetApiV1KnowledgeBasesByIdFilesResponses, GetApiV1KnowledgeBasesByIdResponse, GetApiV1KnowledgeBasesByIdResponses, GetApiV1KnowledgeBasesData, GetApiV1KnowledgeBasesError, GetApiV1KnowledgeBasesErrors, GetApiV1KnowledgeBasesResponse, GetApiV1KnowledgeBasesResponses, GetApiV1McpServersByIdData, GetApiV1McpServersByIdError, GetApiV1McpServersByIdErrors, GetApiV1McpServersByIdResponse, GetApiV1McpServersByIdResponses, GetApiV1McpServersData, GetApiV1McpServersError, GetApiV1McpServersErrors, GetApiV1McpServersResponse, GetApiV1McpServersResponses, GetApiV1MemoriesByCategoryData, GetApiV1MemoriesByCategoryError, GetApiV1MemoriesByCategoryErrors, GetApiV1MemoriesByCategoryResponse, GetApiV1MemoriesByCategoryResponses, GetApiV1MemoriesPersonaData, GetApiV1MemoriesPersonaError, GetApiV1MemoriesPersonaErrors, GetApiV1MemoriesPersonaResponse, GetApiV1MemoriesPersonaResponses, GetApiV1MemoriesPersonaVersionsData, GetApiV1MemoriesPersonaVersionsError, GetApiV1MemoriesPersonaVersionsErrors, GetApiV1MemoriesPersonaVersionsResponse, GetApiV1MemoriesPersonaVersionsResponses, GetApiV1MessagesByIdData, GetApiV1MessagesByIdError, GetApiV1MessagesByIdErrors, GetApiV1MessagesByIdResponse, GetApiV1MessagesByIdResponses, GetApiV1MessagesCountData, GetApiV1MessagesCountError, GetApiV1MessagesCountErrors, GetApiV1MessagesCountResponse, GetApiV1MessagesCountResponses, GetApiV1MessagesData, GetApiV1MessagesError, GetApiV1MessagesErrors, GetApiV1MessagesResponse, GetApiV1MessagesResponses, GetApiV1MessageTranslationsByMessageIdData, GetApiV1MessageTranslationsByMessageIdError, GetApiV1MessageTranslationsByMessageIdErrors, GetApiV1MessageTranslationsByMessageIdResponse, GetApiV1MessageTranslationsByMessageIdResponses, GetApiV1ModelsByProviderIdByModelIdData, GetApiV1ModelsByProviderIdByModelIdError, GetApiV1ModelsByProviderIdByModelIdErrors, GetApiV1ModelsByProviderIdByModelIdResponse, GetApiV1ModelsByProviderIdByModelIdResponses, GetApiV1ModelsData, GetApiV1ModelsError, GetApiV1ModelsErrors, GetApiV1ModelsResponse, GetApiV1ModelsResponses, GetApiV1NotificationsCountsData, GetApiV1NotificationsCountsError, GetApiV1NotificationsCountsErrors, GetApiV1NotificationsCountsResponse, GetApiV1NotificationsCountsResponses, GetApiV1NotificationsData, GetApiV1NotificationsError, GetApiV1NotificationsErrors, GetApiV1NotificationsResponse, GetApiV1NotificationsResponses, GetApiV1NotificationsSettingsData, GetApiV1NotificationsSettingsError, GetApiV1NotificationsSettingsErrors, GetApiV1NotificationsSettingsResponse, GetApiV1NotificationsSettingsResponses, GetApiV1NotificationsUnreadCountData, GetApiV1NotificationsUnreadCountError, GetApiV1NotificationsUnreadCountErrors, GetApiV1NotificationsUnreadCountResponse, GetApiV1NotificationsUnreadCountResponses, GetApiV1PermissionsByIdData, GetApiV1PermissionsByIdError, GetApiV1PermissionsByIdErrors, GetApiV1PermissionsByIdResponse, GetApiV1PermissionsByIdResponses, GetApiV1PermissionsData, GetApiV1PermissionsError, GetApiV1PermissionsErrors, GetApiV1PermissionsResponse, GetApiV1PermissionsResponses, GetApiV1PluginsData, GetApiV1PluginsError, GetApiV1PluginsErrors, GetApiV1PluginsResponse, GetApiV1PluginsResponses, GetApiV1ProvidersByIdData, GetApiV1ProvidersByIdError, GetApiV1ProvidersByIdErrors, GetApiV1ProvidersByIdResponse, GetApiV1ProvidersByIdResponses, GetApiV1ProvidersData, GetApiV1ProvidersError, GetApiV1ProvidersErrors, GetApiV1ProvidersResponse, GetApiV1ProvidersResponses, GetApiV1RolesByIdData, GetApiV1RolesByIdError, GetApiV1RolesByIdErrors, GetApiV1RolesByIdPermissionsData, GetApiV1RolesByIdPermissionsError, GetApiV1RolesByIdPermissionsErrors, GetApiV1RolesByIdPermissionsResponse, GetApiV1RolesByIdPermissionsResponses, GetApiV1RolesByIdResponse, GetApiV1RolesByIdResponses, GetApiV1RolesData, GetApiV1RolesError, GetApiV1RolesErrors, GetApiV1RolesResponse, GetApiV1RolesResponses, GetApiV1SignalsReceiptsData, GetApiV1SignalsReceiptsError, GetApiV1SignalsReceiptsErrors, GetApiV1SignalsReceiptsResponse, GetApiV1SignalsReceiptsResponses, GetApiV1TasksByIdData, GetApiV1TasksByIdError, GetApiV1TasksByIdErrors, GetApiV1TasksByIdResponse, GetApiV1TasksByIdResponses, GetApiV1TasksByIdRunsData, GetApiV1TasksByIdRunsError, GetApiV1TasksByIdRunsErrors, GetApiV1TasksByIdRunsResponse, GetApiV1TasksByIdRunsResponses, GetApiV1TasksData, GetApiV1TasksError, GetApiV1TasksErrors, GetApiV1TasksResponse, GetApiV1TasksResponses, GetApiV1TopicsByIdData, GetApiV1TopicsByIdError, GetApiV1TopicsByIdErrors, GetApiV1TopicsByIdResponse, GetApiV1TopicsByIdResponses, GetApiV1TopicsByTopicIdThreadsData, GetApiV1TopicsByTopicIdThreadsError, GetApiV1TopicsByTopicIdThreadsErrors, GetApiV1TopicsByTopicIdThreadsResponse, GetApiV1TopicsByTopicIdThreadsResponses, GetApiV1TopicsData, GetApiV1TopicsError, GetApiV1TopicsErrors, GetApiV1TopicsResponse, GetApiV1TopicsResponses, GetApiV1UsageData, GetApiV1UsageError, GetApiV1UsageErrors, GetApiV1UsageResponse, GetApiV1UsageResponses, GetApiV1UsersByIdData, GetApiV1UsersByIdError, GetApiV1UsersByIdErrors, GetApiV1UsersByIdResponse, GetApiV1UsersByIdResponses, GetApiV1UsersByIdRolesData, GetApiV1UsersByIdRolesError, GetApiV1UsersByIdRolesErrors, GetApiV1UsersByIdRolesResponse, GetApiV1UsersByIdRolesResponses, GetApiV1UsersData, GetApiV1UsersError, GetApiV1UsersErrors, GetApiV1UsersMeData, GetApiV1UsersMeError, GetApiV1UsersMeErrors, GetApiV1UsersMeResponse, GetApiV1UsersMeResponses, GetApiV1UsersResponse, GetApiV1UsersResponses, Goal, GoalAdvanceResult, GoalDecisionOption, GoalGraph, GoalGraphDecision, GoalGraphEdge, GoalGraphEvent, GoalGraphNode, GoalGraphSnapshot, GoalGraphWorkVersionLink, GoalList, GoalListItem, GoalRestartResult, GoalSupervision, IdempotencyKey, ImMessage, ImReadResult, ImSendResult, ImSyncResult, InstalledPlugin, InstalledPluginList, KnowledgeBase, KnowledgeBaseDetail, KnowledgeBaseFileOperationResult, KnowledgeBaseList, KnowledgeBaseListItem, McpServer, McpServerSyncResult, McpServerTool, MemoryActivity, MemoryCategoryEntries, MemoryContext, MemoryExperience, MemoryIdentity, MemoryPersona, MemoryPersonaVersion, MemoryPreference, Message, MessageTranslation, MessageTranslationWrite, Model, Notification, NotificationCategoryCount, NotificationSettings, NotificationUnreadCount, PageHasMore, PageNextCursor, PageTotal, PatchApiV1AgentGroupsByIdData, PatchApiV1AgentGroupsByIdError, PatchApiV1AgentGroupsByIdErrors, PatchApiV1AgentGroupsByIdResponse, PatchApiV1AgentGroupsByIdResponses, PatchApiV1AgentsByIdAccountsByAccountIdData, PatchApiV1AgentsByIdAccountsByAccountIdError, PatchApiV1AgentsByIdAccountsByAccountIdErrors, PatchApiV1AgentsByIdAccountsByAccountIdResponse, PatchApiV1AgentsByIdAccountsByAccountIdResponses, PatchApiV1AgentsByIdData, PatchApiV1AgentsByIdError, PatchApiV1AgentsByIdErrors, PatchApiV1AgentsByIdResponse, PatchApiV1AgentsByIdResponses, PatchApiV1ApiKeysByIdData, PatchApiV1ApiKeysByIdError, PatchApiV1ApiKeysByIdErrors, PatchApiV1ApiKeysByIdResponse, PatchApiV1ApiKeysByIdResponses, PatchApiV1ChatGroupsByIdData, PatchApiV1ChatGroupsByIdError, PatchApiV1ChatGroupsByIdErrors, PatchApiV1ChatGroupsByIdResponse, PatchApiV1ChatGroupsByIdResponses, PatchApiV1EvalBenchmarksByIdData, PatchApiV1EvalBenchmarksByIdError, PatchApiV1EvalBenchmarksByIdErrors, PatchApiV1EvalBenchmarksByIdResponse, PatchApiV1EvalBenchmarksByIdResponses, PatchApiV1EvalDatasetsByIdData, PatchApiV1EvalDatasetsByIdError, PatchApiV1EvalDatasetsByIdErrors, PatchApiV1EvalDatasetsByIdResponse, PatchApiV1EvalDatasetsByIdResponses, PatchApiV1EvalRunsByIdStatusData, PatchApiV1EvalRunsByIdStatusError, PatchApiV1EvalRunsByIdStatusErrors, PatchApiV1EvalRunsByIdStatusResponse, PatchApiV1EvalRunsByIdStatusResponses, PatchApiV1EvalTestCasesByIdData, PatchApiV1EvalTestCasesByIdError, PatchApiV1EvalTestCasesByIdErrors, PatchApiV1EvalTestCasesByIdResponse, PatchApiV1EvalTestCasesByIdResponses, PatchApiV1FilesByIdData, PatchApiV1FilesByIdError, PatchApiV1FilesByIdErrors, PatchApiV1FilesByIdResponse, PatchApiV1FilesByIdResponses, PatchApiV1GoalsByIdData, PatchApiV1GoalsByIdError, PatchApiV1GoalsByIdErrors, PatchApiV1GoalsByIdResponse, PatchApiV1GoalsByIdResponses, PatchApiV1KnowledgeBasesByIdData, PatchApiV1KnowledgeBasesByIdError, PatchApiV1KnowledgeBasesByIdErrors, PatchApiV1KnowledgeBasesByIdResponse, PatchApiV1KnowledgeBasesByIdResponses, PatchApiV1McpServersByIdData, PatchApiV1McpServersByIdError, PatchApiV1McpServersByIdErrors, PatchApiV1McpServersByIdResponse, PatchApiV1McpServersByIdResponses, PatchApiV1MessageTranslationsByMessageIdData, PatchApiV1MessageTranslationsByMessageIdError, PatchApiV1MessageTranslationsByMessageIdErrors, PatchApiV1MessageTranslationsByMessageIdResponse, PatchApiV1MessageTranslationsByMessageIdResponses, PatchApiV1ModelsByProviderIdByModelIdData, PatchApiV1ModelsByProviderIdByModelIdError, PatchApiV1ModelsByProviderIdByModelIdErrors, PatchApiV1ModelsByProviderIdByModelIdResponse, PatchApiV1ModelsByProviderIdByModelIdResponses, PatchApiV1NotificationsSettingsData, PatchApiV1NotificationsSettingsError, PatchApiV1NotificationsSettingsErrors, PatchApiV1NotificationsSettingsResponse, PatchApiV1NotificationsSettingsResponses, PatchApiV1PermissionsByIdData, PatchApiV1PermissionsByIdError, PatchApiV1PermissionsByIdErrors, PatchApiV1PermissionsByIdResponse, PatchApiV1PermissionsByIdResponses, PatchApiV1ProvidersByIdData, PatchApiV1ProvidersByIdError, PatchApiV1ProvidersByIdErrors, PatchApiV1ProvidersByIdResponse, PatchApiV1ProvidersByIdResponses, PatchApiV1RolesByIdData, PatchApiV1RolesByIdError, PatchApiV1RolesByIdErrors, PatchApiV1RolesByIdPermissionsData, PatchApiV1RolesByIdPermissionsError, PatchApiV1RolesByIdPermissionsErrors, PatchApiV1RolesByIdPermissionsResponse, PatchApiV1RolesByIdPermissionsResponses, PatchApiV1RolesByIdResponse, PatchApiV1RolesByIdResponses, PatchApiV1TasksByIdData, PatchApiV1TasksByIdError, PatchApiV1TasksByIdErrors, PatchApiV1TasksByIdResponse, PatchApiV1TasksByIdResponses, PatchApiV1TasksByIdStatusData, PatchApiV1TasksByIdStatusError, PatchApiV1TasksByIdStatusErrors, PatchApiV1TasksByIdStatusResponse, PatchApiV1TasksByIdStatusResponses, PatchApiV1TopicsByIdData, PatchApiV1TopicsByIdError, PatchApiV1TopicsByIdErrors, PatchApiV1TopicsByIdResponse, PatchApiV1TopicsByIdResponses, PatchApiV1UsersByIdData, PatchApiV1UsersByIdError, PatchApiV1UsersByIdErrors, PatchApiV1UsersByIdResponse, PatchApiV1UsersByIdResponses, PatchApiV1UsersByIdRolesData, PatchApiV1UsersByIdRolesError, PatchApiV1UsersByIdRolesErrors, PatchApiV1UsersByIdRolesResponse, PatchApiV1UsersByIdRolesResponses, Permission, PermissionList, PostApiV1AgentGroupsData, PostApiV1AgentGroupsError, PostApiV1AgentGroupsErrors, PostApiV1AgentGroupsResponse, PostApiV1AgentGroupsResponses, PostApiV1AgentsByIdAccountsData, PostApiV1AgentsByIdAccountsError, PostApiV1AgentsByIdAccountsErrors, PostApiV1AgentsByIdAccountsResponse, PostApiV1AgentsByIdAccountsResponses, PostApiV1AgentsByIdDuplicateData, PostApiV1AgentsByIdDuplicateError, PostApiV1AgentsByIdDuplicateErrors, PostApiV1AgentsByIdDuplicateResponse, PostApiV1AgentsByIdDuplicateResponses, PostApiV1AgentsData, PostApiV1AgentsError, PostApiV1AgentsErrors, PostApiV1AgentsResponse, PostApiV1AgentsResponses, PostApiV1ApiKeysData, PostApiV1ApiKeysError, PostApiV1ApiKeysErrors, PostApiV1ApiKeysResponse, PostApiV1ApiKeysResponses, PostApiV1AudioSpeechData, PostApiV1AudioSpeechError, PostApiV1AudioSpeechErrors, PostApiV1AudioSpeechResponse, PostApiV1AudioSpeechResponses, PostApiV1ChatData, PostApiV1ChatError, PostApiV1ChatErrors, PostApiV1ChatGenerateReplyData, PostApiV1ChatGenerateReplyError, PostApiV1ChatGenerateReplyErrors, PostApiV1ChatGenerateReplyResponse, PostApiV1ChatGenerateReplyResponses, PostApiV1ChatGroupsByIdMembersData, PostApiV1ChatGroupsByIdMembersError, PostApiV1ChatGroupsByIdMembersErrors, PostApiV1ChatGroupsByIdMembersResponse, PostApiV1ChatGroupsByIdMembersResponses, PostApiV1ChatGroupsData, PostApiV1ChatGroupsError, PostApiV1ChatGroupsErrors, PostApiV1ChatGroupsResponse, PostApiV1ChatGroupsResponses, PostApiV1ChatResponse, PostApiV1ChatResponses, PostApiV1ChatTranslateData, PostApiV1ChatTranslateError, PostApiV1ChatTranslateErrors, PostApiV1ChatTranslateResponse, PostApiV1ChatTranslateResponses, PostApiV1EvalBenchmarksData, PostApiV1EvalBenchmarksError, PostApiV1EvalBenchmarksErrors, PostApiV1EvalBenchmarksResponse, PostApiV1EvalBenchmarksResponses, PostApiV1EvalDatasetsByDatasetIdTestCasesData, PostApiV1EvalDatasetsByDatasetIdTestCasesError, PostApiV1EvalDatasetsByDatasetIdTestCasesErrors, PostApiV1EvalDatasetsByDatasetIdTestCasesResponse, PostApiV1EvalDatasetsByDatasetIdTestCasesResponses, PostApiV1EvalDatasetsData, PostApiV1EvalDatasetsError, PostApiV1EvalDatasetsErrors, PostApiV1EvalDatasetsResponse, PostApiV1EvalDatasetsResponses, PostApiV1EvalRunsByIdClaimData, PostApiV1EvalRunsByIdClaimError, PostApiV1EvalRunsByIdClaimErrors, PostApiV1EvalRunsByIdClaimResponse, PostApiV1EvalRunsByIdClaimResponses, PostApiV1EvalRunsByIdResultsData, PostApiV1EvalRunsByIdResultsError, PostApiV1EvalRunsByIdResultsErrors, PostApiV1EvalRunsByIdResultsResponse, PostApiV1EvalRunsByIdResultsResponses, PostApiV1EvalRunsByIdRetryErrorsData, PostApiV1EvalRunsByIdRetryErrorsError, PostApiV1EvalRunsByIdRetryErrorsErrors, PostApiV1EvalRunsByIdRetryErrorsResponse, PostApiV1EvalRunsByIdRetryErrorsResponses, PostApiV1EvalRunsData, PostApiV1EvalRunsError, PostApiV1EvalRunsErrors, PostApiV1EvalRunsResponse, PostApiV1EvalRunsResponses, PostApiV1FilesBatchesData, PostApiV1FilesBatchesError, PostApiV1FilesBatchesErrors, PostApiV1FilesBatchesResponse, PostApiV1FilesBatchesResponses, PostApiV1FilesByIdChunksData, PostApiV1FilesByIdChunksError, PostApiV1FilesByIdChunksErrors, PostApiV1FilesByIdChunksResponse, PostApiV1FilesByIdChunksResponses, PostApiV1FilesByIdParsesData, PostApiV1FilesByIdParsesError, PostApiV1FilesByIdParsesErrors, PostApiV1FilesByIdParsesResponse, PostApiV1FilesByIdParsesResponses, PostApiV1FilesData, PostApiV1FilesError, PostApiV1FilesErrors, PostApiV1FilesQueriesData, PostApiV1FilesQueriesError, PostApiV1FilesQueriesErrors, PostApiV1FilesQueriesResponse, PostApiV1FilesQueriesResponses, PostApiV1FilesResponse, PostApiV1FilesResponses, PostApiV1GoalsByIdAdvanceData, PostApiV1GoalsByIdAdvanceError, PostApiV1GoalsByIdAdvanceErrors, PostApiV1GoalsByIdAdvanceResponse, PostApiV1GoalsByIdAdvanceResponses, PostApiV1GoalsByIdPauseData, PostApiV1GoalsByIdPauseError, PostApiV1GoalsByIdPauseErrors, PostApiV1GoalsByIdPauseResponse, PostApiV1GoalsByIdPauseResponses, PostApiV1GoalsByIdRestartData, PostApiV1GoalsByIdRestartError, PostApiV1GoalsByIdRestartErrors, PostApiV1GoalsByIdRestartResponse, PostApiV1GoalsByIdRestartResponses, PostApiV1GoalsByIdResumeData, PostApiV1GoalsByIdResumeError, PostApiV1GoalsByIdResumeErrors, PostApiV1GoalsByIdResumeResponse, PostApiV1GoalsByIdResumeResponses, PostApiV1GoalsData, PostApiV1GoalsError, PostApiV1GoalsErrors, PostApiV1GoalsResponse, PostApiV1GoalsResponses, PostApiV1ImMessagesData, PostApiV1ImMessagesError, PostApiV1ImMessagesErrors, PostApiV1ImMessagesResponse, PostApiV1ImMessagesResponses, PostApiV1ImTopicsByTopicIdReadData, PostApiV1ImTopicsByTopicIdReadError, PostApiV1ImTopicsByTopicIdReadErrors, PostApiV1ImTopicsByTopicIdReadResponse, PostApiV1ImTopicsByTopicIdReadResponses, PostApiV1KnowledgeBasesByIdFilesBatchData, PostApiV1KnowledgeBasesByIdFilesBatchError, PostApiV1KnowledgeBasesByIdFilesBatchErrors, PostApiV1KnowledgeBasesByIdFilesBatchResponse, PostApiV1KnowledgeBasesByIdFilesBatchResponses, PostApiV1KnowledgeBasesByIdFilesMoveData, PostApiV1KnowledgeBasesByIdFilesMoveError, PostApiV1KnowledgeBasesByIdFilesMoveErrors, PostApiV1KnowledgeBasesByIdFilesMoveResponse, PostApiV1KnowledgeBasesByIdFilesMoveResponses, PostApiV1KnowledgeBasesData, PostApiV1KnowledgeBasesError, PostApiV1KnowledgeBasesErrors, PostApiV1KnowledgeBasesResponse, PostApiV1KnowledgeBasesResponses, PostApiV1McpServersByIdSyncData, PostApiV1McpServersByIdSyncError, PostApiV1McpServersByIdSyncErrors, PostApiV1McpServersByIdSyncResponse, PostApiV1McpServersByIdSyncResponses, PostApiV1McpServersData, PostApiV1McpServersError, PostApiV1McpServersErrors, PostApiV1McpServersResponse, PostApiV1McpServersResponses, PostApiV1MessagesData, PostApiV1MessagesError, PostApiV1MessagesErrors, PostApiV1MessagesRepliesData, PostApiV1MessagesRepliesError, PostApiV1MessagesRepliesErrors, PostApiV1MessagesRepliesResponse, PostApiV1MessagesRepliesResponses, PostApiV1MessagesResponse, PostApiV1MessagesResponses, PostApiV1MessageTranslationsByMessageIdData, PostApiV1MessageTranslationsByMessageIdError, PostApiV1MessageTranslationsByMessageIdErrors, PostApiV1MessageTranslationsByMessageIdResponse, PostApiV1MessageTranslationsByMessageIdResponses, PostApiV1ModelsData, PostApiV1ModelsError, PostApiV1ModelsErrors, PostApiV1ModelsResponse, PostApiV1ModelsResponses, PostApiV1NotificationsArchiveAllData, PostApiV1NotificationsArchiveAllError, PostApiV1NotificationsArchiveAllErrors, PostApiV1NotificationsArchiveAllResponse, PostApiV1NotificationsArchiveAllResponses, PostApiV1NotificationsByIdArchiveData, PostApiV1NotificationsByIdArchiveError, PostApiV1NotificationsByIdArchiveErrors, PostApiV1NotificationsByIdArchiveResponse, PostApiV1NotificationsByIdArchiveResponses, PostApiV1NotificationsReadAllData, PostApiV1NotificationsReadAllError, PostApiV1NotificationsReadAllErrors, PostApiV1NotificationsReadAllResponse, PostApiV1NotificationsReadAllResponses, PostApiV1NotificationsReadData, PostApiV1NotificationsReadError, PostApiV1NotificationsReadErrors, PostApiV1NotificationsReadResponse, PostApiV1NotificationsReadResponses, PostApiV1PermissionsData, PostApiV1PermissionsError, PostApiV1PermissionsErrors, PostApiV1PermissionsResponse, PostApiV1PermissionsResponses, PostApiV1ProvidersData, PostApiV1ProvidersError, PostApiV1ProvidersErrors, PostApiV1ProvidersResponse, PostApiV1ProvidersResponses, PostApiV1ResponsesData, PostApiV1ResponsesError, PostApiV1ResponsesErrors, PostApiV1ResponsesResponse, PostApiV1ResponsesResponses, PostApiV1RolesData, PostApiV1RolesError, PostApiV1RolesErrors, PostApiV1RolesResponse, PostApiV1RolesResponses, PostApiV1SignalsSourceEventsData, PostApiV1SignalsSourceEventsError, PostApiV1SignalsSourceEventsErrors, PostApiV1SignalsSourceEventsResponse, PostApiV1SignalsSourceEventsResponses, PostApiV1SignalsTriggerData, PostApiV1SignalsTriggerError, PostApiV1SignalsTriggerErrors, PostApiV1SignalsTriggerResponse, PostApiV1SignalsTriggerResponses, PostApiV1TasksByIdRunsData, PostApiV1TasksByIdRunsError, PostApiV1TasksByIdRunsErrors, PostApiV1TasksByIdRunsResponse, PostApiV1TasksByIdRunsResponses, PostApiV1TasksData, PostApiV1TasksError, PostApiV1TasksErrors, PostApiV1TasksResponse, PostApiV1TasksResponses, PostApiV1TopicsData, PostApiV1TopicsError, PostApiV1TopicsErrors, PostApiV1TopicsResponse, PostApiV1TopicsResponses, PostApiV1UsersData, PostApiV1UsersError, PostApiV1UsersErrors, PostApiV1UsersResponse, PostApiV1UsersResponses, Provider, PushTokenRegistration, PutApiV1AgentsByIdAccountsByAccountIdCredentialData, PutApiV1AgentsByIdAccountsByAccountIdCredentialError, PutApiV1AgentsByIdAccountsByAccountIdCredentialErrors, PutApiV1AgentsByIdAccountsByAccountIdCredentialResponse, PutApiV1AgentsByIdAccountsByAccountIdCredentialResponses, PutApiV1EvalRunsByRunIdTopicsByTopicIdResultData, PutApiV1EvalRunsByRunIdTopicsByTopicIdResultError, PutApiV1EvalRunsByRunIdTopicsByTopicIdResultErrors, PutApiV1EvalRunsByRunIdTopicsByTopicIdResultResponse, PutApiV1EvalRunsByRunIdTopicsByTopicIdResultResponses, PutApiV1PushTokensByDeviceIdData, PutApiV1PushTokensByDeviceIdError, PutApiV1PushTokensByDeviceIdErrors, PutApiV1PushTokensByDeviceIdResponse, PutApiV1PushTokensByDeviceIdResponses, ResponseError, ResponseFunctionCall, ResponseFunctionCallOutput, ResponseObject, ResponseOutputItem, ResponseOutputMessage, ResponseOutputText, ResponseUsage, Role, RoleList, RolePermission, RolePermissionList, RolePermissionsUpdateResult, Task, TaskDetail, TaskDetailActivity, TaskDetailSubtask, TaskDetailWorkspaceNode, TaskLabelRef, TaskList, TaskListItem, TaskRun, TaskRunStarted, TaskStatusUpdateResult, Topic, TopicSummary, TopicThread, Usage, User, UserIdentity, UserList, UserRole } from './types.gen';+export { AgentGroups, Agents, ApiKeys, Audio, Chat, ChatGroups, Documents, Eval, Files, Goals, Health, Im, KnowledgeBases, LobeHub, McpServers, Memories, Messages, MessageTranslations, Models, Notifications, type Options, Permissions, Plugins, Providers, PushTokens, Responses, Roles, Signals, Tasks, Topics, Usage as Usage2, Users } from './sdk.gen';+export type { Agent, AgentAccount, AgentAccountCapabilities, AgentAccountList, AgentDetail, AgentFile, AgentGroup, AgentKnowledgeBase, AgentList, AgentPlugin, AgentSignalEmission, AgentSignalReceipt, AgentSignalReceiptList, ApiError, ApiErrorCode, ApiKey, AsyncTaskError, BatchFileUploadResult, BatchGetFilesResult, ChatGenerateReplyResponse, ChatGroup, ChatGroupList, ChatGroupMember, ChatResponse, ChatTranslateResponse, ClientOptions, CreatedAgentGroup, CreatedApiKey, DeleteApiV1AgentGroupsByIdData, DeleteApiV1AgentGroupsByIdError, DeleteApiV1AgentGroupsByIdErrors, DeleteApiV1AgentGroupsByIdResponse, DeleteApiV1AgentGroupsByIdResponses, DeleteApiV1AgentsByIdAccountsByAccountIdData, DeleteApiV1AgentsByIdAccountsByAccountIdError, DeleteApiV1AgentsByIdAccountsByAccountIdErrors, DeleteApiV1AgentsByIdAccountsByAccountIdResponse, DeleteApiV1AgentsByIdAccountsByAccountIdResponses, DeleteApiV1AgentsByIdData, DeleteApiV1AgentsByIdError, DeleteApiV1AgentsByIdErrors, DeleteApiV1AgentsByIdResponse, DeleteApiV1AgentsByIdResponses, DeleteApiV1ApiKeysByIdData, DeleteApiV1ApiKeysByIdError, DeleteApiV1ApiKeysByIdErrors, DeleteApiV1ApiKeysByIdResponse, DeleteApiV1ApiKeysByIdResponses, DeleteApiV1ChatGroupsByIdData, DeleteApiV1ChatGroupsByIdError, DeleteApiV1ChatGroupsByIdErrors, DeleteApiV1ChatGroupsByIdMembersData, DeleteApiV1ChatGroupsByIdMembersError, DeleteApiV1ChatGroupsByIdMembersErrors, DeleteApiV1ChatGroupsByIdMembersResponse, DeleteApiV1ChatGroupsByIdMembersResponses, DeleteApiV1ChatGroupsByIdResponse, DeleteApiV1ChatGroupsByIdResponses, DeleteApiV1EvalBenchmarksByIdData, DeleteApiV1EvalBenchmarksByIdError, DeleteApiV1EvalBenchmarksByIdErrors, DeleteApiV1EvalBenchmarksByIdResponse, DeleteApiV1EvalBenchmarksByIdResponses, DeleteApiV1EvalDatasetsByIdData, DeleteApiV1EvalDatasetsByIdError, DeleteApiV1EvalDatasetsByIdErrors, DeleteApiV1EvalDatasetsByIdResponse, DeleteApiV1EvalDatasetsByIdResponses, DeleteApiV1EvalTestCasesByIdData, DeleteApiV1EvalTestCasesByIdError, DeleteApiV1EvalTestCasesByIdErrors, DeleteApiV1EvalTestCasesByIdResponse, DeleteApiV1EvalTestCasesByIdResponses, DeleteApiV1FilesByIdData, DeleteApiV1FilesByIdError, DeleteApiV1FilesByIdErrors, DeleteApiV1FilesByIdResponse, DeleteApiV1FilesByIdResponses, DeleteApiV1GoalsByIdData, DeleteApiV1GoalsByIdError, DeleteApiV1GoalsByIdErrors, DeleteApiV1GoalsByIdResponse, DeleteApiV1GoalsByIdResponses, DeleteApiV1KnowledgeBasesByIdData, DeleteApiV1KnowledgeBasesByIdError, DeleteApiV1KnowledgeBasesByIdErrors, DeleteApiV1KnowledgeBasesByIdFilesBatchData, DeleteApiV1KnowledgeBasesByIdFilesBatchError, DeleteApiV1KnowledgeBasesByIdFilesBatchErrors, DeleteApiV1KnowledgeBasesByIdFilesBatchResponse, DeleteApiV1KnowledgeBasesByIdFilesBatchResponses, DeleteApiV1KnowledgeBasesByIdResponse, DeleteApiV1KnowledgeBasesByIdResponses, DeleteApiV1McpServersByIdData, DeleteApiV1McpServersByIdError, DeleteApiV1McpServersByIdErrors, DeleteApiV1McpServersByIdResponse, DeleteApiV1McpServersByIdResponses, DeleteApiV1MemoriesByCategoryByIdData, DeleteApiV1MemoriesByCategoryByIdError, DeleteApiV1MemoriesByCategoryByIdErrors, DeleteApiV1MemoriesByCategoryByIdResponse, DeleteApiV1MemoriesByCategoryByIdResponses, DeleteApiV1MemoriesData, DeleteApiV1MemoriesError, DeleteApiV1MemoriesErrors, DeleteApiV1MemoriesResponse, DeleteApiV1MemoriesResponses, DeleteApiV1MessagesByIdData, DeleteApiV1MessagesByIdError, DeleteApiV1MessagesByIdErrors, DeleteApiV1MessagesByIdResponse, DeleteApiV1MessagesByIdResponses, DeleteApiV1MessagesData, DeleteApiV1MessagesError, DeleteApiV1MessagesErrors, DeleteApiV1MessagesResponse, DeleteApiV1MessagesResponses, DeleteApiV1MessageTranslationsByMessageIdData, DeleteApiV1MessageTranslationsByMessageIdError, DeleteApiV1MessageTranslationsByMessageIdErrors, DeleteApiV1MessageTranslationsByMessageIdResponse, DeleteApiV1MessageTranslationsByMessageIdResponses, DeleteApiV1PermissionsByIdData, DeleteApiV1PermissionsByIdError, DeleteApiV1PermissionsByIdErrors, DeleteApiV1PermissionsByIdResponse, DeleteApiV1PermissionsByIdResponses, DeleteApiV1ProvidersByIdData, DeleteApiV1ProvidersByIdError, DeleteApiV1ProvidersByIdErrors, DeleteApiV1ProvidersByIdResponse, DeleteApiV1ProvidersByIdResponses, DeleteApiV1PushTokensByDeviceIdData, DeleteApiV1PushTokensByDeviceIdError, DeleteApiV1PushTokensByDeviceIdErrors, DeleteApiV1PushTokensByDeviceIdResponse, DeleteApiV1PushTokensByDeviceIdResponses, DeleteApiV1RolesByIdData, DeleteApiV1RolesByIdError, DeleteApiV1RolesByIdErrors, DeleteApiV1RolesByIdPermissionsData, DeleteApiV1RolesByIdPermissionsError, DeleteApiV1RolesByIdPermissionsErrors, DeleteApiV1RolesByIdPermissionsResponse, DeleteApiV1RolesByIdPermissionsResponses, DeleteApiV1RolesByIdResponse, DeleteApiV1RolesByIdResponses, DeleteApiV1TasksByIdData, DeleteApiV1TasksByIdError, DeleteApiV1TasksByIdErrors, DeleteApiV1TasksByIdResponse, DeleteApiV1TasksByIdResponses, DeleteApiV1TopicsByIdData, DeleteApiV1TopicsByIdError, DeleteApiV1TopicsByIdErrors, DeleteApiV1TopicsByIdResponse, DeleteApiV1TopicsByIdResponses, DeleteApiV1UsersByIdData, DeleteApiV1UsersByIdError, DeleteApiV1UsersByIdErrors, DeleteApiV1UsersByIdResponse, DeleteApiV1UsersByIdResponses, DeleteApiV1UsersByIdRolesData, DeleteApiV1UsersByIdRolesError, DeleteApiV1UsersByIdRolesErrors, DeleteApiV1UsersByIdRolesResponse, DeleteApiV1UsersByIdRolesResponses, DeletedResource, DeletedResources, Document, DocumentSummary, EvalBatchReportResult, EvalBenchmark, EvalBenchmarkRubric, EvalCaseResult, EvalDataset, EvalReportReceipt, EvalReportResult, EvalRetryErrors, EvalRubricScore, EvalRun, EvalRunMetrics, EvalRunResult, EvalRunTopic, EvalStoredResult, EvalTestCase, EvalThreadResult, File, FileAsyncTask, FileChunkStatus, FileChunkTask, FileDetail, FileKnowledgeBaseRef, FileList, FileListItem, FileParseResult, FileUrl, FileUser, GetApiV1AgentGroupsByIdData, GetApiV1AgentGroupsByIdError, GetApiV1AgentGroupsByIdErrors, GetApiV1AgentGroupsByIdResponse, GetApiV1AgentGroupsByIdResponses, GetApiV1AgentGroupsData, GetApiV1AgentGroupsError, GetApiV1AgentGroupsErrors, GetApiV1AgentGroupsResponse, GetApiV1AgentGroupsResponses, GetApiV1AgentsByIdAccountsByAccountIdData, GetApiV1AgentsByIdAccountsByAccountIdError, GetApiV1AgentsByIdAccountsByAccountIdErrors, GetApiV1AgentsByIdAccountsByAccountIdResponse, GetApiV1AgentsByIdAccountsByAccountIdResponses, GetApiV1AgentsByIdAccountsData, GetApiV1AgentsByIdAccountsError, GetApiV1AgentsByIdAccountsErrors, GetApiV1AgentsByIdAccountsResponse, GetApiV1AgentsByIdAccountsResponses, GetApiV1AgentsByIdData, GetApiV1AgentsByIdError, GetApiV1AgentsByIdErrors, GetApiV1AgentsByIdResponse, GetApiV1AgentsByIdResponses, GetApiV1AgentsData, GetApiV1AgentsError, GetApiV1AgentsErrors, GetApiV1AgentsResponse, GetApiV1AgentsResponses, GetApiV1ApiKeysByIdData, GetApiV1ApiKeysByIdError, GetApiV1ApiKeysByIdErrors, GetApiV1ApiKeysByIdResponse, GetApiV1ApiKeysByIdResponses, GetApiV1ApiKeysData, GetApiV1ApiKeysError, GetApiV1ApiKeysErrors, GetApiV1ApiKeysResponse, GetApiV1ApiKeysResponses, GetApiV1ChatGroupsByIdData, GetApiV1ChatGroupsByIdError, GetApiV1ChatGroupsByIdErrors, GetApiV1ChatGroupsByIdResponse, GetApiV1ChatGroupsByIdResponses, GetApiV1ChatGroupsData, GetApiV1ChatGroupsError, GetApiV1ChatGroupsErrors, GetApiV1ChatGroupsResponse, GetApiV1ChatGroupsResponses, GetApiV1DocumentsByIdData, GetApiV1DocumentsByIdError, GetApiV1DocumentsByIdErrors, GetApiV1DocumentsByIdResponse, GetApiV1DocumentsByIdResponses, GetApiV1DocumentsData, GetApiV1DocumentsError, GetApiV1DocumentsErrors, GetApiV1DocumentsResponse, GetApiV1DocumentsResponses, GetApiV1EvalBenchmarksByIdData, GetApiV1EvalBenchmarksByIdError, GetApiV1EvalBenchmarksByIdErrors, GetApiV1EvalBenchmarksByIdResponse, GetApiV1EvalBenchmarksByIdResponses, GetApiV1EvalBenchmarksData, GetApiV1EvalBenchmarksError, GetApiV1EvalBenchmarksErrors, GetApiV1EvalBenchmarksResponse, GetApiV1EvalBenchmarksResponses, GetApiV1EvalDatasetsByDatasetIdTestCasesData, GetApiV1EvalDatasetsByDatasetIdTestCasesError, GetApiV1EvalDatasetsByDatasetIdTestCasesErrors, GetApiV1EvalDatasetsByDatasetIdTestCasesResponse, GetApiV1EvalDatasetsByDatasetIdTestCasesResponses, GetApiV1EvalDatasetsByIdData, GetApiV1EvalDatasetsByIdError, GetApiV1EvalDatasetsByIdErrors, GetApiV1EvalDatasetsByIdResponse, GetApiV1EvalDatasetsByIdResponses, GetApiV1EvalDatasetsData, GetApiV1EvalDatasetsError, GetApiV1EvalDatasetsErrors, GetApiV1EvalDatasetsResponse, GetApiV1EvalDatasetsResponses, GetApiV1EvalRunsByIdData, GetApiV1EvalRunsByIdError, GetApiV1EvalRunsByIdErrors, GetApiV1EvalRunsByIdResponse, GetApiV1EvalRunsByIdResponses, GetApiV1EvalRunsByIdResultsData, GetApiV1EvalRunsByIdResultsError, GetApiV1EvalRunsByIdResultsErrors, GetApiV1EvalRunsByIdResultsResponse, GetApiV1EvalRunsByIdResultsResponses, GetApiV1EvalRunsByIdTopicsData, GetApiV1EvalRunsByIdTopicsError, GetApiV1EvalRunsByIdTopicsErrors, GetApiV1EvalRunsByIdTopicsResponse, GetApiV1EvalRunsByIdTopicsResponses, GetApiV1EvalRunsData, GetApiV1EvalRunsError, GetApiV1EvalRunsErrors, GetApiV1EvalRunsResponse, GetApiV1EvalRunsResponses, GetApiV1EvalTestCasesByIdData, GetApiV1EvalTestCasesByIdError, GetApiV1EvalTestCasesByIdErrors, GetApiV1EvalTestCasesByIdResponse, GetApiV1EvalTestCasesByIdResponses, GetApiV1FilesByIdChunksData, GetApiV1FilesByIdChunksError, GetApiV1FilesByIdChunksErrors, GetApiV1FilesByIdChunksResponse, GetApiV1FilesByIdChunksResponses, GetApiV1FilesByIdData, GetApiV1FilesByIdError, GetApiV1FilesByIdErrors, GetApiV1FilesByIdResponse, GetApiV1FilesByIdResponses, GetApiV1FilesByIdUrlData, GetApiV1FilesByIdUrlError, GetApiV1FilesByIdUrlErrors, GetApiV1FilesByIdUrlResponse, GetApiV1FilesByIdUrlResponses, GetApiV1FilesData, GetApiV1FilesError, GetApiV1FilesErrors, GetApiV1FilesResponse, GetApiV1FilesResponses, GetApiV1GoalsByIdData, GetApiV1GoalsByIdError, GetApiV1GoalsByIdErrors, GetApiV1GoalsByIdResponse, GetApiV1GoalsByIdResponses, GetApiV1GoalsByIdSupervisionData, GetApiV1GoalsByIdSupervisionError, GetApiV1GoalsByIdSupervisionErrors, GetApiV1GoalsByIdSupervisionResponse, GetApiV1GoalsByIdSupervisionResponses, GetApiV1GoalsData, GetApiV1GoalsError, GetApiV1GoalsErrors, GetApiV1GoalsResponse, GetApiV1GoalsResponses, GetApiV1HealthData, GetApiV1HealthResponse, GetApiV1HealthResponses, GetApiV1ImTopicsByTopicIdSyncData, GetApiV1ImTopicsByTopicIdSyncError, GetApiV1ImTopicsByTopicIdSyncErrors, GetApiV1ImTopicsByTopicIdSyncResponse, GetApiV1ImTopicsByTopicIdSyncResponses, GetApiV1KnowledgeBasesByIdData, GetApiV1KnowledgeBasesByIdError, GetApiV1KnowledgeBasesByIdErrors, GetApiV1KnowledgeBasesByIdFilesData, GetApiV1KnowledgeBasesByIdFilesError, GetApiV1KnowledgeBasesByIdFilesErrors, GetApiV1KnowledgeBasesByIdFilesResponse, GetApiV1KnowledgeBasesByIdFilesResponses, GetApiV1KnowledgeBasesByIdResponse, GetApiV1KnowledgeBasesByIdResponses, GetApiV1KnowledgeBasesData, GetApiV1KnowledgeBasesError, GetApiV1KnowledgeBasesErrors, GetApiV1KnowledgeBasesResponse, GetApiV1KnowledgeBasesResponses, GetApiV1McpServersByIdData, GetApiV1McpServersByIdError, GetApiV1McpServersByIdErrors, GetApiV1McpServersByIdResponse, GetApiV1McpServersByIdResponses, GetApiV1McpServersData, GetApiV1McpServersError, GetApiV1McpServersErrors, GetApiV1McpServersResponse, GetApiV1McpServersResponses, GetApiV1MemoriesByCategoryData, GetApiV1MemoriesByCategoryError, GetApiV1MemoriesByCategoryErrors, GetApiV1MemoriesByCategoryResponse, GetApiV1MemoriesByCategoryResponses, GetApiV1MemoriesPersonaData, GetApiV1MemoriesPersonaError, GetApiV1MemoriesPersonaErrors, GetApiV1MemoriesPersonaResponse, GetApiV1MemoriesPersonaResponses, GetApiV1MemoriesPersonaVersionsData, GetApiV1MemoriesPersonaVersionsError, GetApiV1MemoriesPersonaVersionsErrors, GetApiV1MemoriesPersonaVersionsResponse, GetApiV1MemoriesPersonaVersionsResponses, GetApiV1MessagesByIdData, GetApiV1MessagesByIdError, GetApiV1MessagesByIdErrors, GetApiV1MessagesByIdResponse, GetApiV1MessagesByIdResponses, GetApiV1MessagesCountData, GetApiV1MessagesCountError, GetApiV1MessagesCountErrors, GetApiV1MessagesCountResponse, GetApiV1MessagesCountResponses, GetApiV1MessagesData, GetApiV1MessagesError, GetApiV1MessagesErrors, GetApiV1MessagesResponse, GetApiV1MessagesResponses, GetApiV1MessageTranslationsByMessageIdData, GetApiV1MessageTranslationsByMessageIdError, GetApiV1MessageTranslationsByMessageIdErrors, GetApiV1MessageTranslationsByMessageIdResponse, GetApiV1MessageTranslationsByMessageIdResponses, GetApiV1ModelsByProviderIdByModelIdData, GetApiV1ModelsByProviderIdByModelIdError, GetApiV1ModelsByProviderIdByModelIdErrors, GetApiV1ModelsByProviderIdByModelIdResponse, GetApiV1ModelsByProviderIdByModelIdResponses, GetApiV1ModelsData, GetApiV1ModelsError, GetApiV1ModelsErrors, GetApiV1ModelsResponse, GetApiV1ModelsResponses, GetApiV1NotificationsCountsData, GetApiV1NotificationsCountsError, GetApiV1NotificationsCountsErrors, GetApiV1NotificationsCountsResponse, GetApiV1NotificationsCountsResponses, GetApiV1NotificationsData, GetApiV1NotificationsError, GetApiV1NotificationsErrors, GetApiV1NotificationsResponse, GetApiV1NotificationsResponses, GetApiV1NotificationsSettingsData, GetApiV1NotificationsSettingsError, GetApiV1NotificationsSettingsErrors, GetApiV1NotificationsSettingsResponse, GetApiV1NotificationsSettingsResponses, GetApiV1NotificationsUnreadCountData, GetApiV1NotificationsUnreadCountError, GetApiV1NotificationsUnreadCountErrors, GetApiV1NotificationsUnreadCountResponse, GetApiV1NotificationsUnreadCountResponses, GetApiV1PermissionsByIdData, GetApiV1PermissionsByIdError, GetApiV1PermissionsByIdErrors, GetApiV1PermissionsByIdResponse, GetApiV1PermissionsByIdResponses, GetApiV1PermissionsData, GetApiV1PermissionsError, GetApiV1PermissionsErrors, GetApiV1PermissionsResponse, GetApiV1PermissionsResponses, GetApiV1PluginsData, GetApiV1PluginsError, GetApiV1PluginsErrors, GetApiV1PluginsResponse, GetApiV1PluginsResponses, GetApiV1ProvidersByIdData, GetApiV1ProvidersByIdError, GetApiV1ProvidersByIdErrors, GetApiV1ProvidersByIdResponse, GetApiV1ProvidersByIdResponses, GetApiV1ProvidersData, GetApiV1ProvidersError, GetApiV1ProvidersErrors, GetApiV1ProvidersResponse, GetApiV1ProvidersResponses, GetApiV1RolesByIdData, GetApiV1RolesByIdError, GetApiV1RolesByIdErrors, GetApiV1RolesByIdPermissionsData, GetApiV1RolesByIdPermissionsError, GetApiV1RolesByIdPermissionsErrors, GetApiV1RolesByIdPermissionsResponse, GetApiV1RolesByIdPermissionsResponses, GetApiV1RolesByIdResponse, GetApiV1RolesByIdResponses, GetApiV1RolesData, GetApiV1RolesError, GetApiV1RolesErrors, GetApiV1RolesResponse, GetApiV1RolesResponses, GetApiV1SignalsReceiptsData, GetApiV1SignalsReceiptsError, GetApiV1SignalsReceiptsErrors, GetApiV1SignalsReceiptsResponse, GetApiV1SignalsReceiptsResponses, GetApiV1TasksByIdData, GetApiV1TasksByIdError, GetApiV1TasksByIdErrors, GetApiV1TasksByIdResponse, GetApiV1TasksByIdResponses, GetApiV1TasksByIdRunsData, GetApiV1TasksByIdRunsError, GetApiV1TasksByIdRunsErrors, GetApiV1TasksByIdRunsResponse, GetApiV1TasksByIdRunsResponses, GetApiV1TasksData, GetApiV1TasksError, GetApiV1TasksErrors, GetApiV1TasksResponse, GetApiV1TasksResponses, GetApiV1TopicsByIdData, GetApiV1TopicsByIdError, GetApiV1TopicsByIdErrors, GetApiV1TopicsByIdResponse, GetApiV1TopicsByIdResponses, GetApiV1TopicsByTopicIdThreadsData, GetApiV1TopicsByTopicIdThreadsError, GetApiV1TopicsByTopicIdThreadsErrors, GetApiV1TopicsByTopicIdThreadsResponse, GetApiV1TopicsByTopicIdThreadsResponses, GetApiV1TopicsData, GetApiV1TopicsError, GetApiV1TopicsErrors, GetApiV1TopicsResponse, GetApiV1TopicsResponses, GetApiV1UsageData, GetApiV1UsageError, GetApiV1UsageErrors, GetApiV1UsageResponse, GetApiV1UsageResponses, GetApiV1UsersByIdData, GetApiV1UsersByIdError, GetApiV1UsersByIdErrors, GetApiV1UsersByIdResponse, GetApiV1UsersByIdResponses, GetApiV1UsersByIdRolesData, GetApiV1UsersByIdRolesError, GetApiV1UsersByIdRolesErrors, GetApiV1UsersByIdRolesResponse, GetApiV1UsersByIdRolesResponses, GetApiV1UsersData, GetApiV1UsersError, GetApiV1UsersErrors, GetApiV1UsersMeData, GetApiV1UsersMeError, GetApiV1UsersMeErrors, GetApiV1UsersMeResponse, GetApiV1UsersMeResponses, GetApiV1UsersResponse, GetApiV1UsersResponses, Goal, GoalAdvanceResult, GoalDecisionOption, GoalGraph, GoalGraphDecision, GoalGraphEdge, GoalGraphEvent, GoalGraphNode, GoalGraphSnapshot, GoalGraphWorkVersionLink, GoalList, GoalListItem, GoalRestartResult, GoalSupervision, IdempotencyKey, ImMessage, ImReadResult, ImSendResult, ImSyncResult, InstalledPlugin, InstalledPluginList, KnowledgeBase, KnowledgeBaseDetail, KnowledgeBaseFileOperationResult, KnowledgeBaseList, KnowledgeBaseListItem, McpServer, McpServerSyncResult, McpServerTool, MemoryActivity, MemoryCategoryEntries, MemoryContext, MemoryExperience, MemoryIdentity, MemoryPersona, MemoryPersonaVersion, MemoryPreference, Message, MessageTranslation, MessageTranslationWrite, Model, Notification, NotificationCategoryCount, NotificationSettings, NotificationUnreadCount, PageHasMore, PageNextCursor, PageTotal, PatchApiV1AgentGroupsByIdData, PatchApiV1AgentGroupsByIdError, PatchApiV1AgentGroupsByIdErrors, PatchApiV1AgentGroupsByIdResponse, PatchApiV1AgentGroupsByIdResponses, PatchApiV1AgentsByIdAccountsByAccountIdData, PatchApiV1AgentsByIdAccountsByAccountIdError, PatchApiV1AgentsByIdAccountsByAccountIdErrors, PatchApiV1AgentsByIdAccountsByAccountIdResponse, PatchApiV1AgentsByIdAccountsByAccountIdResponses, PatchApiV1AgentsByIdData, PatchApiV1AgentsByIdError, PatchApiV1AgentsByIdErrors, PatchApiV1AgentsByIdResponse, PatchApiV1AgentsByIdResponses, PatchApiV1ApiKeysByIdData, PatchApiV1ApiKeysByIdError, PatchApiV1ApiKeysByIdErrors, PatchApiV1ApiKeysByIdResponse, PatchApiV1ApiKeysByIdResponses, PatchApiV1ChatGroupsByIdData, PatchApiV1ChatGroupsByIdError, PatchApiV1ChatGroupsByIdErrors, PatchApiV1ChatGroupsByIdResponse, PatchApiV1ChatGroupsByIdResponses, PatchApiV1DocumentsByIdData, PatchApiV1DocumentsByIdError, PatchApiV1DocumentsByIdErrors, PatchApiV1DocumentsByIdResponse, PatchApiV1DocumentsByIdResponses, PatchApiV1EvalBenchmarksByIdData, PatchApiV1EvalBenchmarksByIdError, PatchApiV1EvalBenchmarksByIdErrors, PatchApiV1EvalBenchmarksByIdResponse, PatchApiV1EvalBenchmarksByIdResponses, PatchApiV1EvalDatasetsByIdData, PatchApiV1EvalDatasetsByIdError, PatchApiV1EvalDatasetsByIdErrors, PatchApiV1EvalDatasetsByIdResponse, PatchApiV1EvalDatasetsByIdResponses, PatchApiV1EvalRunsByIdStatusData, PatchApiV1EvalRunsByIdStatusError, PatchApiV1EvalRunsByIdStatusErrors, PatchApiV1EvalRunsByIdStatusResponse, PatchApiV1EvalRunsByIdStatusResponses, PatchApiV1EvalTestCasesByIdData, PatchApiV1EvalTestCasesByIdError, PatchApiV1EvalTestCasesByIdErrors, PatchApiV1EvalTestCasesByIdResponse, PatchApiV1EvalTestCasesByIdResponses, PatchApiV1FilesByIdData, PatchApiV1FilesByIdError, PatchApiV1FilesByIdErrors, PatchApiV1FilesByIdResponse, PatchApiV1FilesByIdResponses, PatchApiV1GoalsByIdData, PatchApiV1GoalsByIdError, PatchApiV1GoalsByIdErrors, PatchApiV1GoalsByIdResponse, PatchApiV1GoalsByIdResponses, PatchApiV1KnowledgeBasesByIdData, PatchApiV1KnowledgeBasesByIdError, PatchApiV1KnowledgeBasesByIdErrors, PatchApiV1KnowledgeBasesByIdResponse, PatchApiV1KnowledgeBasesByIdResponses, PatchApiV1McpServersByIdData, PatchApiV1McpServersByIdError, PatchApiV1McpServersByIdErrors, PatchApiV1McpServersByIdResponse, PatchApiV1McpServersByIdResponses, PatchApiV1MessageTranslationsByMessageIdData, PatchApiV1MessageTranslationsByMessageIdError, PatchApiV1MessageTranslationsByMessageIdErrors, PatchApiV1MessageTranslationsByMessageIdResponse, PatchApiV1MessageTranslationsByMessageIdResponses, PatchApiV1ModelsByProviderIdByModelIdData, PatchApiV1ModelsByProviderIdByModelIdError, PatchApiV1ModelsByProviderIdByModelIdErrors, PatchApiV1ModelsByProviderIdByModelIdResponse, PatchApiV1ModelsByProviderIdByModelIdResponses, PatchApiV1NotificationsSettingsData, PatchApiV1NotificationsSettingsError, PatchApiV1NotificationsSettingsErrors, PatchApiV1NotificationsSettingsResponse, PatchApiV1NotificationsSettingsResponses, PatchApiV1PermissionsByIdData, PatchApiV1PermissionsByIdError, PatchApiV1PermissionsByIdErrors, PatchApiV1PermissionsByIdResponse, PatchApiV1PermissionsByIdResponses, PatchApiV1ProvidersByIdData, PatchApiV1ProvidersByIdError, PatchApiV1ProvidersByIdErrors, PatchApiV1ProvidersByIdResponse, PatchApiV1ProvidersByIdResponses, PatchApiV1RolesByIdData, PatchApiV1RolesByIdError, PatchApiV1RolesByIdErrors, PatchApiV1RolesByIdPermissionsData, PatchApiV1RolesByIdPermissionsError, PatchApiV1RolesByIdPermissionsErrors, PatchApiV1RolesByIdPermissionsResponse, PatchApiV1RolesByIdPermissionsResponses, PatchApiV1RolesByIdResponse, PatchApiV1RolesByIdResponses, PatchApiV1TasksByIdData, PatchApiV1TasksByIdError, PatchApiV1TasksByIdErrors, PatchApiV1TasksByIdResponse, PatchApiV1TasksByIdResponses, PatchApiV1TasksByIdStatusData, PatchApiV1TasksByIdStatusError, PatchApiV1TasksByIdStatusErrors, PatchApiV1TasksByIdStatusResponse, PatchApiV1TasksByIdStatusResponses, PatchApiV1TopicsByIdData, PatchApiV1TopicsByIdError, PatchApiV1TopicsByIdErrors, PatchApiV1TopicsByIdResponse, PatchApiV1TopicsByIdResponses, PatchApiV1UsersByIdData, PatchApiV1UsersByIdError, PatchApiV1UsersByIdErrors, PatchApiV1UsersByIdResponse, PatchApiV1UsersByIdResponses, PatchApiV1UsersByIdRolesData, PatchApiV1UsersByIdRolesError, PatchApiV1UsersByIdRolesErrors, PatchApiV1UsersByIdRolesResponse, PatchApiV1UsersByIdRolesResponses, Permission, PermissionList, PostApiV1AgentGroupsData, PostApiV1AgentGroupsError, PostApiV1AgentGroupsErrors, PostApiV1AgentGroupsResponse, PostApiV1AgentGroupsResponses, PostApiV1AgentsByIdAccountsData, PostApiV1AgentsByIdAccountsError, PostApiV1AgentsByIdAccountsErrors, PostApiV1AgentsByIdAccountsResponse, PostApiV1AgentsByIdAccountsResponses, PostApiV1AgentsByIdDuplicateData, PostApiV1AgentsByIdDuplicateError, PostApiV1AgentsByIdDuplicateErrors, PostApiV1AgentsByIdDuplicateResponse, PostApiV1AgentsByIdDuplicateResponses, PostApiV1AgentsData, PostApiV1AgentsError, PostApiV1AgentsErrors, PostApiV1AgentsResponse, PostApiV1AgentsResponses, PostApiV1ApiKeysData, PostApiV1ApiKeysError, PostApiV1ApiKeysErrors, PostApiV1ApiKeysResponse, PostApiV1ApiKeysResponses, PostApiV1AudioSpeechData, PostApiV1AudioSpeechError, PostApiV1AudioSpeechErrors, PostApiV1AudioSpeechResponse, PostApiV1AudioSpeechResponses, PostApiV1ChatData, PostApiV1ChatError, PostApiV1ChatErrors, PostApiV1ChatGenerateReplyData, PostApiV1ChatGenerateReplyError, PostApiV1ChatGenerateReplyErrors, PostApiV1ChatGenerateReplyResponse, PostApiV1ChatGenerateReplyResponses, PostApiV1ChatGroupsByIdMembersData, PostApiV1ChatGroupsByIdMembersError, PostApiV1ChatGroupsByIdMembersErrors, PostApiV1ChatGroupsByIdMembersResponse, PostApiV1ChatGroupsByIdMembersResponses, PostApiV1ChatGroupsData, PostApiV1ChatGroupsError, PostApiV1ChatGroupsErrors, PostApiV1ChatGroupsResponse, PostApiV1ChatGroupsResponses, PostApiV1ChatResponse, PostApiV1ChatResponses, PostApiV1ChatTranslateData, PostApiV1ChatTranslateError, PostApiV1ChatTranslateErrors, PostApiV1ChatTranslateResponse, PostApiV1ChatTranslateResponses, PostApiV1DocumentsData, PostApiV1DocumentsError, PostApiV1DocumentsErrors, PostApiV1DocumentsResponse, PostApiV1DocumentsResponses, PostApiV1EvalBenchmarksData, PostApiV1EvalBenchmarksError, PostApiV1EvalBenchmarksErrors, PostApiV1EvalBenchmarksResponse, PostApiV1EvalBenchmarksResponses, PostApiV1EvalDatasetsByDatasetIdTestCasesData, PostApiV1EvalDatasetsByDatasetIdTestCasesError, PostApiV1EvalDatasetsByDatasetIdTestCasesErrors, PostApiV1EvalDatasetsByDatasetIdTestCasesResponse, PostApiV1EvalDatasetsByDatasetIdTestCasesResponses, PostApiV1EvalDatasetsData, PostApiV1EvalDatasetsError, PostApiV1EvalDatasetsErrors, PostApiV1EvalDatasetsResponse, PostApiV1EvalDatasetsResponses, PostApiV1EvalRunsByIdClaimData, PostApiV1EvalRunsByIdClaimError, PostApiV1EvalRunsByIdClaimErrors, PostApiV1EvalRunsByIdClaimResponse, PostApiV1EvalRunsByIdClaimResponses, PostApiV1EvalRunsByIdResultsData, PostApiV1EvalRunsByIdResultsError, PostApiV1EvalRunsByIdResultsErrors, PostApiV1EvalRunsByIdResultsResponse, PostApiV1EvalRunsByIdResultsResponses, PostApiV1EvalRunsByIdRetryErrorsData, PostApiV1EvalRunsByIdRetryErrorsError, PostApiV1EvalRunsByIdRetryErrorsErrors, PostApiV1EvalRunsByIdRetryErrorsResponse, PostApiV1EvalRunsByIdRetryErrorsResponses, PostApiV1EvalRunsData, PostApiV1EvalRunsError, PostApiV1EvalRunsErrors, PostApiV1EvalRunsResponse, PostApiV1EvalRunsResponses, PostApiV1FilesBatchesData, PostApiV1FilesBatchesError, PostApiV1FilesBatchesErrors, PostApiV1FilesBatchesResponse, PostApiV1FilesBatchesResponses, PostApiV1FilesByIdChunksData, PostApiV1FilesByIdChunksError, PostApiV1FilesByIdChunksErrors, PostApiV1FilesByIdChunksResponse, PostApiV1FilesByIdChunksResponses, PostApiV1FilesByIdParsesData, PostApiV1FilesByIdParsesError, PostApiV1FilesByIdParsesErrors, PostApiV1FilesByIdParsesResponse, PostApiV1FilesByIdParsesResponses, PostApiV1FilesData, PostApiV1FilesError, PostApiV1FilesErrors, PostApiV1FilesQueriesData, PostApiV1FilesQueriesError, PostApiV1FilesQueriesErrors, PostApiV1FilesQueriesResponse, PostApiV1FilesQueriesResponses, PostApiV1FilesResponse, PostApiV1FilesResponses, PostApiV1GoalsByIdAdvanceData, PostApiV1GoalsByIdAdvanceError, PostApiV1GoalsByIdAdvanceErrors, PostApiV1GoalsByIdAdvanceResponse, PostApiV1GoalsByIdAdvanceResponses, PostApiV1GoalsByIdPauseData, PostApiV1GoalsByIdPauseError, PostApiV1GoalsByIdPauseErrors, PostApiV1GoalsByIdPauseResponse, PostApiV1GoalsByIdPauseResponses, PostApiV1GoalsByIdRestartData, PostApiV1GoalsByIdRestartError, PostApiV1GoalsByIdRestartErrors, PostApiV1GoalsByIdRestartResponse, PostApiV1GoalsByIdRestartResponses, PostApiV1GoalsByIdResumeData, PostApiV1GoalsByIdResumeError, PostApiV1GoalsByIdResumeErrors, PostApiV1GoalsByIdResumeResponse, PostApiV1GoalsByIdResumeResponses, PostApiV1GoalsData, PostApiV1GoalsError, PostApiV1GoalsErrors, PostApiV1GoalsResponse, PostApiV1GoalsResponses, PostApiV1ImMessagesData, PostApiV1ImMessagesError, PostApiV1ImMessagesErrors, PostApiV1ImMessagesResponse, PostApiV1ImMessagesResponses, PostApiV1ImTopicsByTopicIdReadData, PostApiV1ImTopicsByTopicIdReadError, PostApiV1ImTopicsByTopicIdReadErrors, PostApiV1ImTopicsByTopicIdReadResponse, PostApiV1ImTopicsByTopicIdReadResponses, PostApiV1KnowledgeBasesByIdFilesBatchData, PostApiV1KnowledgeBasesByIdFilesBatchError, PostApiV1KnowledgeBasesByIdFilesBatchErrors, PostApiV1KnowledgeBasesByIdFilesBatchResponse, PostApiV1KnowledgeBasesByIdFilesBatchResponses, PostApiV1KnowledgeBasesByIdFilesMoveData, PostApiV1KnowledgeBasesByIdFilesMoveError, PostApiV1KnowledgeBasesByIdFilesMoveErrors, PostApiV1KnowledgeBasesByIdFilesMoveResponse, PostApiV1KnowledgeBasesByIdFilesMoveResponses, PostApiV1KnowledgeBasesData, PostApiV1KnowledgeBasesError, PostApiV1KnowledgeBasesErrors, PostApiV1KnowledgeBasesResponse, PostApiV1KnowledgeBasesResponses, PostApiV1McpServersByIdSyncData, PostApiV1McpServersByIdSyncError, PostApiV1McpServersByIdSyncErrors, PostApiV1McpServersByIdSyncResponse, PostApiV1McpServersByIdSyncResponses, PostApiV1McpServersData, PostApiV1McpServersError, PostApiV1McpServersErrors, PostApiV1McpServersResponse, PostApiV1McpServersResponses, PostApiV1MessagesData, PostApiV1MessagesError, PostApiV1MessagesErrors, PostApiV1MessagesRepliesData, PostApiV1MessagesRepliesError, PostApiV1MessagesRepliesErrors, PostApiV1MessagesRepliesResponse, PostApiV1MessagesRepliesResponses, PostApiV1MessagesResponse, PostApiV1MessagesResponses, PostApiV1MessageTranslationsByMessageIdData, PostApiV1MessageTranslationsByMessageIdError, PostApiV1MessageTranslationsByMessageIdErrors, PostApiV1MessageTranslationsByMessageIdResponse, PostApiV1MessageTranslationsByMessageIdResponses, PostApiV1ModelsData, PostApiV1ModelsError, PostApiV1ModelsErrors, PostApiV1ModelsResponse, PostApiV1ModelsResponses, PostApiV1NotificationsArchiveAllData, PostApiV1NotificationsArchiveAllError, PostApiV1NotificationsArchiveAllErrors, PostApiV1NotificationsArchiveAllResponse, PostApiV1NotificationsArchiveAllResponses, PostApiV1NotificationsByIdArchiveData, PostApiV1NotificationsByIdArchiveError, PostApiV1NotificationsByIdArchiveErrors, PostApiV1NotificationsByIdArchiveResponse, PostApiV1NotificationsByIdArchiveResponses, PostApiV1NotificationsReadAllData, PostApiV1NotificationsReadAllError, PostApiV1NotificationsReadAllErrors, PostApiV1NotificationsReadAllResponse, PostApiV1NotificationsReadAllResponses, PostApiV1NotificationsReadData, PostApiV1NotificationsReadError, PostApiV1NotificationsReadErrors, PostApiV1NotificationsReadResponse, PostApiV1NotificationsReadResponses, PostApiV1PermissionsData, PostApiV1PermissionsError, PostApiV1PermissionsErrors, PostApiV1PermissionsResponse, PostApiV1PermissionsResponses, PostApiV1ProvidersData, PostApiV1ProvidersError, PostApiV1ProvidersErrors, PostApiV1ProvidersResponse, PostApiV1ProvidersResponses, PostApiV1ResponsesData, PostApiV1ResponsesError, PostApiV1ResponsesErrors, PostApiV1ResponsesResponse, PostApiV1ResponsesResponses, PostApiV1RolesData, PostApiV1RolesError, PostApiV1RolesErrors, PostApiV1RolesResponse, PostApiV1RolesResponses, PostApiV1SignalsSourceEventsData, PostApiV1SignalsSourceEventsError, PostApiV1SignalsSourceEventsErrors, PostApiV1SignalsSourceEventsResponse, PostApiV1SignalsSourceEventsResponses, PostApiV1SignalsTriggerData, PostApiV1SignalsTriggerError, PostApiV1SignalsTriggerErrors, PostApiV1SignalsTriggerResponse, PostApiV1SignalsTriggerResponses, PostApiV1TasksByIdRunsData, PostApiV1TasksByIdRunsError, PostApiV1TasksByIdRunsErrors, PostApiV1TasksByIdRunsResponse, PostApiV1TasksByIdRunsResponses, PostApiV1TasksData, PostApiV1TasksError, PostApiV1TasksErrors, PostApiV1TasksResponse, PostApiV1TasksResponses, PostApiV1TopicsData, PostApiV1TopicsError, PostApiV1TopicsErrors, PostApiV1TopicsResponse, PostApiV1TopicsResponses, PostApiV1UsersData, PostApiV1UsersError, PostApiV1UsersErrors, PostApiV1UsersResponse, PostApiV1UsersResponses, Provider, PushTokenRegistration, PutApiV1AgentsByIdAccountsByAccountIdCredentialData, PutApiV1AgentsByIdAccountsByAccountIdCredentialError, PutApiV1AgentsByIdAccountsByAccountIdCredentialErrors, PutApiV1AgentsByIdAccountsByAccountIdCredentialResponse, PutApiV1AgentsByIdAccountsByAccountIdCredentialResponses, PutApiV1EvalRunsByRunIdTopicsByTopicIdResultData, PutApiV1EvalRunsByRunIdTopicsByTopicIdResultError, PutApiV1EvalRunsByRunIdTopicsByTopicIdResultErrors, PutApiV1EvalRunsByRunIdTopicsByTopicIdResultResponse, PutApiV1EvalRunsByRunIdTopicsByTopicIdResultResponses, PutApiV1PushTokensByDeviceIdData, PutApiV1PushTokensByDeviceIdError, PutApiV1PushTokensByDeviceIdErrors, PutApiV1PushTokensByDeviceIdResponse, PutApiV1PushTokensByDeviceIdResponses, ResponseError, ResponseFunctionCall, ResponseFunctionCallOutput, ResponseObject, ResponseOutputItem, ResponseOutputMessage, ResponseOutputText, ResponseUsage, Role, RoleList, RolePermission, RolePermissionList, RolePermissionsUpdateResult, Task, TaskDetail, TaskDetailActivity, TaskDetailSubtask, TaskDetailWorkspaceNode, TaskLabelRef, TaskList, TaskListItem, TaskRun, TaskRunStarted, TaskStatusUpdateResult, Topic, TopicSummary, TopicThread, Usage, User, UserIdentity, UserList, UserRole } from './types.gen';diff --git a/packages/sdk/src/generated/sdk.gen.ts b/packages/sdk/src/generated/sdk.gen.tsindex 38ea6ed46f5..e7bf9744c0d 100644--- a/packages/sdk/src/generated/sdk.gen.ts+++ b/packages/sdk/src/generated/sdk.gen.ts@@ -2,7 +2,7 @@import { type Client, type ClientMeta, formDataBodySerializer, type Options as Options2, type RequestResult, type TDataShape } from './client';import { client } from './client.gen';-import type { DeleteApiV1AgentGroupsByIdData, DeleteApiV1AgentGroupsByIdErrors, DeleteApiV1AgentGroupsByIdResponses, DeleteApiV1AgentsByIdAccountsByAccountIdData, DeleteApiV1AgentsByIdAccountsByAccountIdErrors, DeleteApiV1AgentsByIdAccountsByAccountIdResponses, DeleteApiV1AgentsByIdData, DeleteApiV1AgentsByIdErrors, DeleteApiV1AgentsByIdResponses, DeleteApiV1ApiKeysByIdData, DeleteApiV1ApiKeysByIdErrors, DeleteApiV1ApiKeysByIdResponses, DeleteApiV1ChatGroupsByIdData, DeleteApiV1ChatGroupsByIdErrors, DeleteApiV1ChatGroupsByIdMembersData, DeleteApiV1ChatGroupsByIdMembersErrors, DeleteApiV1ChatGroupsByIdMembersResponses, DeleteApiV1ChatGroupsByIdResponses, DeleteApiV1EvalBenchmarksByIdData, DeleteApiV1EvalBenchmarksByIdErrors, DeleteApiV1EvalBenchmarksByIdResponses, DeleteApiV1EvalDatasetsByIdData, DeleteApiV1EvalDatasetsByIdErrors, DeleteApiV1EvalDatasetsByIdResponses, DeleteApiV1EvalTestCasesByIdData, DeleteApiV1EvalTestCasesByIdErrors, DeleteApiV1EvalTestCasesByIdResponses, DeleteApiV1FilesByIdData, DeleteApiV1FilesByIdErrors, DeleteApiV1FilesByIdResponses, DeleteApiV1GoalsByIdData, DeleteApiV1GoalsByIdErrors, DeleteApiV1GoalsByIdResponses, DeleteApiV1KnowledgeBasesByIdData, DeleteApiV1KnowledgeBasesByIdErrors, DeleteApiV1KnowledgeBasesByIdFilesBatchData, DeleteApiV1KnowledgeBasesByIdFilesBatchErrors, DeleteApiV1KnowledgeBasesByIdFilesBatchResponses, DeleteApiV1KnowledgeBasesByIdResponses, DeleteApiV1McpServersByIdData, DeleteApiV1McpServersByIdErrors, DeleteApiV1McpServersByIdResponses, DeleteApiV1MemoriesByCategoryByIdData, DeleteApiV1MemoriesByCategoryByIdErrors, DeleteApiV1MemoriesByCategoryByIdResponses, DeleteApiV1MemoriesData, DeleteApiV1MemoriesErrors, DeleteApiV1MemoriesResponses, DeleteApiV1MessagesByIdData, DeleteApiV1MessagesByIdErrors, DeleteApiV1MessagesByIdResponses, DeleteApiV1MessagesData, DeleteApiV1MessagesErrors, DeleteApiV1MessagesResponses, DeleteApiV1MessageTranslationsByMessageIdData, DeleteApiV1MessageTranslationsByMessageIdErrors, DeleteApiV1MessageTranslationsByMessageIdResponses, DeleteApiV1PermissionsByIdData, DeleteApiV1PermissionsByIdErrors, DeleteApiV1PermissionsByIdResponses, DeleteApiV1ProvidersByIdData, DeleteApiV1ProvidersByIdErrors, DeleteApiV1ProvidersByIdResponses, DeleteApiV1PushTokensByDeviceIdData, DeleteApiV1PushTokensByDeviceIdErrors, DeleteApiV1PushTokensByDeviceIdResponses, DeleteApiV1RolesByIdData, DeleteApiV1RolesByIdErrors, DeleteApiV1RolesByIdPermissionsData, DeleteApiV1RolesByIdPermissionsErrors, DeleteApiV1RolesByIdPermissionsResponses, DeleteApiV1RolesByIdResponses, DeleteApiV1TasksByIdData, DeleteApiV1TasksByIdErrors, DeleteApiV1TasksByIdResponses, DeleteApiV1TopicsByIdData, DeleteApiV1TopicsByIdErrors, DeleteApiV1TopicsByIdResponses, DeleteApiV1UsersByIdData, DeleteApiV1UsersByIdErrors, DeleteApiV1UsersByIdResponses, DeleteApiV1UsersByIdRolesData, DeleteApiV1UsersByIdRolesErrors, DeleteApiV1UsersByIdRolesResponses, GetApiV1AgentGroupsByIdData, GetApiV1AgentGroupsByIdErrors, GetApiV1AgentGroupsByIdResponses, GetApiV1AgentGroupsData, GetApiV1AgentGroupsErrors, GetApiV1AgentGroupsResponses, GetApiV1AgentsByIdAccountsByAccountIdData, GetApiV1AgentsByIdAccountsByAccountIdErrors, GetApiV1AgentsByIdAccountsByAccountIdResponses, GetApiV1AgentsByIdAccountsData, GetApiV1AgentsByIdAccountsErrors, GetApiV1AgentsByIdAccountsResponses, GetApiV1AgentsByIdData, GetApiV1AgentsByIdErrors, GetApiV1AgentsByIdResponses, GetApiV1AgentsData, GetApiV1AgentsErrors, GetApiV1AgentsResponses, GetApiV1ApiKeysByIdData, GetApiV1ApiKeysByIdErrors, GetApiV1ApiKeysByIdResponses, GetApiV1ApiKeysData, GetApiV1ApiKeysErrors, GetApiV1ApiKeysResponses, GetApiV1ChatGroupsByIdData, GetApiV1ChatGroupsByIdErrors, GetApiV1ChatGroupsByIdResponses, GetApiV1ChatGroupsData, GetApiV1ChatGroupsErrors, GetApiV1ChatGroupsResponses, GetApiV1EvalBenchmarksByIdData, GetApiV1EvalBenchmarksByIdErrors, GetApiV1EvalBenchmarksByIdResponses, GetApiV1EvalBenchmarksData, GetApiV1EvalBenchmarksErrors, GetApiV1EvalBenchmarksResponses, GetApiV1EvalDatasetsByDatasetIdTestCasesData, GetApiV1EvalDatasetsByDatasetIdTestCasesErrors, GetApiV1EvalDatasetsByDatasetIdTestCasesResponses, GetApiV1EvalDatasetsByIdData, GetApiV1EvalDatasetsByIdErrors, GetApiV1EvalDatasetsByIdResponses, GetApiV1EvalDatasetsData, GetApiV1EvalDatasetsErrors, GetApiV1EvalDatasetsResponses, GetApiV1EvalRunsByIdData, GetApiV1EvalRunsByIdErrors, GetApiV1EvalRunsByIdResponses, GetApiV1EvalRunsByIdResultsData, GetApiV1EvalRunsByIdResultsErrors, GetApiV1EvalRunsByIdResultsResponses, GetApiV1EvalRunsByIdTopicsData, GetApiV1EvalRunsByIdTopicsErrors, GetApiV1EvalRunsByIdTopicsResponses, GetApiV1EvalRunsData, GetApiV1EvalRunsErrors, GetApiV1EvalRunsResponses, GetApiV1EvalTestCasesByIdData, GetApiV1EvalTestCasesByIdErrors, GetApiV1EvalTestCasesByIdResponses, GetApiV1FilesByIdChunksData, GetApiV1FilesByIdChunksErrors, GetApiV1FilesByIdChunksResponses, GetApiV1FilesByIdData, GetApiV1FilesByIdErrors, GetApiV1FilesByIdResponses, GetApiV1FilesByIdUrlData, GetApiV1FilesByIdUrlErrors, GetApiV1FilesByIdUrlResponses, GetApiV1FilesData, GetApiV1FilesErrors, GetApiV1FilesResponses, GetApiV1GoalsByIdData, GetApiV1GoalsByIdErrors, GetApiV1GoalsByIdResponses, GetApiV1GoalsByIdSupervisionData, GetApiV1GoalsByIdSupervisionErrors, GetApiV1GoalsByIdSupervisionResponses, GetApiV1GoalsData, GetApiV1GoalsErrors, GetApiV1GoalsResponses, GetApiV1HealthData, GetApiV1HealthResponses, GetApiV1ImTopicsByTopicIdSyncData, GetApiV1ImTopicsByTopicIdSyncErrors, GetApiV1ImTopicsByTopicIdSyncResponses, GetApiV1KnowledgeBasesByIdData, GetApiV1KnowledgeBasesByIdErrors, GetApiV1KnowledgeBasesByIdFilesData, GetApiV1KnowledgeBasesByIdFilesErrors, GetApiV1KnowledgeBasesByIdFilesResponses, GetApiV1KnowledgeBasesByIdResponses, GetApiV1KnowledgeBasesData, GetApiV1KnowledgeBasesErrors, GetApiV1KnowledgeBasesResponses, GetApiV1McpServersByIdData, GetApiV1McpServersByIdErrors, GetApiV1McpServersByIdResponses, GetApiV1McpServersData, GetApiV1McpServersErrors, GetApiV1McpServersResponses, GetApiV1MemoriesByCategoryData, GetApiV1MemoriesByCategoryErrors, GetApiV1MemoriesByCategoryResponses, GetApiV1MemoriesPersonaData, GetApiV1MemoriesPersonaErrors, GetApiV1MemoriesPersonaResponses, GetApiV1MemoriesPersonaVersionsData, GetApiV1MemoriesPersonaVersionsErrors, GetApiV1MemoriesPersonaVersionsResponses, GetApiV1MessagesByIdData, GetApiV1MessagesByIdErrors, GetApiV1MessagesByIdResponses, GetApiV1MessagesCountData, GetApiV1MessagesCountErrors, GetApiV1MessagesCountResponses, GetApiV1MessagesData, GetApiV1MessagesErrors, GetApiV1MessagesResponses, GetApiV1MessageTranslationsByMessageIdData, GetApiV1MessageTranslationsByMessageIdErrors, GetApiV1MessageTranslationsByMessageIdResponses, GetApiV1ModelsByProviderIdByModelIdData, GetApiV1ModelsByProviderIdByModelIdErrors, GetApiV1ModelsByProviderIdByModelIdResponses, GetApiV1ModelsData, GetApiV1ModelsErrors, GetApiV1ModelsResponses, GetApiV1NotificationsCountsData, GetApiV1NotificationsCountsErrors, GetApiV1NotificationsCountsResponses, GetApiV1NotificationsData, GetApiV1NotificationsErrors, GetApiV1NotificationsResponses, GetApiV1NotificationsSettingsData, GetApiV1NotificationsSettingsErrors, GetApiV1NotificationsSettingsResponses, GetApiV1NotificationsUnreadCountData, GetApiV1NotificationsUnreadCountErrors, GetApiV1NotificationsUnreadCountResponses, GetApiV1PermissionsByIdData, GetApiV1PermissionsByIdErrors, GetApiV1PermissionsByIdResponses, GetApiV1PermissionsData, GetApiV1PermissionsErrors, GetApiV1PermissionsResponses, GetApiV1PluginsData, GetApiV1PluginsErrors, GetApiV1PluginsResponses, GetApiV1ProvidersByIdData, GetApiV1ProvidersByIdErrors, GetApiV1ProvidersByIdResponses, GetApiV1ProvidersData, GetApiV1ProvidersErrors, GetApiV1ProvidersResponses, GetApiV1RolesByIdData, GetApiV1RolesByIdErrors, GetApiV1RolesByIdPermissionsData, GetApiV1RolesByIdPermissionsErrors, GetApiV1RolesByIdPermissionsResponses, GetApiV1RolesByIdResponses, GetApiV1RolesData, GetApiV1RolesErrors, GetApiV1RolesResponses, GetApiV1SignalsReceiptsData, GetApiV1SignalsReceiptsErrors, GetApiV1SignalsReceiptsResponses, GetApiV1TasksByIdData, GetApiV1TasksByIdErrors, GetApiV1TasksByIdResponses, GetApiV1TasksByIdRunsData, GetApiV1TasksByIdRunsErrors, GetApiV1TasksByIdRunsResponses, GetApiV1TasksData, GetApiV1TasksErrors, GetApiV1TasksResponses, GetApiV1TopicsByIdData, GetApiV1TopicsByIdErrors, GetApiV1TopicsByIdResponses, GetApiV1TopicsByTopicIdThreadsData, GetApiV1TopicsByTopicIdThreadsErrors, GetApiV1TopicsByTopicIdThreadsResponses, GetApiV1TopicsData, GetApiV1TopicsErrors, GetApiV1TopicsResponses, GetApiV1UsageData, GetApiV1UsageErrors, GetApiV1UsageResponses, GetApiV1UsersByIdData, GetApiV1UsersByIdErrors, GetApiV1UsersByIdResponses, GetApiV1UsersByIdRolesData, GetApiV1UsersByIdRolesErrors, GetApiV1UsersByIdRolesResponses, GetApiV1UsersData, GetApiV1UsersErrors, GetApiV1UsersMeData, GetApiV1UsersMeErrors, GetApiV1UsersMeResponses, GetApiV1UsersResponses, PatchApiV1AgentGroupsByIdData, PatchApiV1AgentGroupsByIdErrors, PatchApiV1AgentGroupsByIdResponses, PatchApiV1AgentsByIdAccountsByAccountIdData, PatchApiV1AgentsByIdAccountsByAccountIdErrors, PatchApiV1AgentsByIdAccountsByAccountIdResponses, PatchApiV1AgentsByIdData, PatchApiV1AgentsByIdErrors, PatchApiV1AgentsByIdResponses, PatchApiV1ApiKeysByIdData, PatchApiV1ApiKeysByIdErrors, PatchApiV1ApiKeysByIdResponses, PatchApiV1ChatGroupsByIdData, PatchApiV1ChatGroupsByIdErrors, PatchApiV1ChatGroupsByIdResponses, PatchApiV1EvalBenchmarksByIdData, PatchApiV1EvalBenchmarksByIdErrors, PatchApiV1EvalBenchmarksByIdResponses, PatchApiV1EvalDatasetsByIdData, PatchApiV1EvalDatasetsByIdErrors, PatchApiV1EvalDatasetsByIdResponses, PatchApiV1EvalRunsByIdStatusData, PatchApiV1EvalRunsByIdStatusErrors, PatchApiV1EvalRunsByIdStatusResponses, PatchApiV1EvalTestCasesByIdData, PatchApiV1EvalTestCasesByIdErrors, PatchApiV1EvalTestCasesByIdResponses, PatchApiV1FilesByIdData, PatchApiV1FilesByIdErrors, PatchApiV1FilesByIdResponses, PatchApiV1GoalsByIdData, PatchApiV1GoalsByIdErrors, PatchApiV1GoalsByIdResponses, PatchApiV1KnowledgeBasesByIdData, PatchApiV1KnowledgeBasesByIdErrors, PatchApiV1KnowledgeBasesByIdResponses, PatchApiV1McpServersByIdData, PatchApiV1McpServersByIdErrors, PatchApiV1McpServersByIdResponses, PatchApiV1MessageTranslationsByMessageIdData, PatchApiV1MessageTranslationsByMessageIdErrors, PatchApiV1MessageTranslationsByMessageIdResponses, PatchApiV1ModelsByProviderIdByModelIdData, PatchApiV1ModelsByProviderIdByModelIdErrors, PatchApiV1ModelsByProviderIdByModelIdResponses, PatchApiV1NotificationsSettingsData, PatchApiV1NotificationsSettingsErrors, PatchApiV1NotificationsSettingsResponses, PatchApiV1PermissionsByIdData, PatchApiV1PermissionsByIdErrors, PatchApiV1PermissionsByIdResponses, PatchApiV1ProvidersByIdData, PatchApiV1ProvidersByIdErrors, PatchApiV1ProvidersByIdResponses, PatchApiV1RolesByIdData, PatchApiV1RolesByIdErrors, PatchApiV1RolesByIdPermissionsData, PatchApiV1RolesByIdPermissionsErrors, PatchApiV1RolesByIdPermissionsResponses, PatchApiV1RolesByIdResponses, PatchApiV1TasksByIdData, PatchApiV1TasksByIdErrors, PatchApiV1TasksByIdResponses, PatchApiV1TasksByIdStatusData, PatchApiV1TasksByIdStatusErrors, PatchApiV1TasksByIdStatusResponses, PatchApiV1TopicsByIdData, PatchApiV1TopicsByIdErrors, PatchApiV1TopicsByIdResponses, PatchApiV1UsersByIdData, PatchApiV1UsersByIdErrors, PatchApiV1UsersByIdResponses, PatchApiV1UsersByIdRolesData, PatchApiV1UsersByIdRolesErrors, PatchApiV1UsersByIdRolesResponses, PostApiV1AgentGroupsData, PostApiV1AgentGroupsErrors, PostApiV1AgentGroupsResponses, PostApiV1AgentsByIdAccountsData, PostApiV1AgentsByIdAccountsErrors, PostApiV1AgentsByIdAccountsResponses, PostApiV1AgentsByIdDuplicateData, PostApiV1AgentsByIdDuplicateErrors, PostApiV1AgentsByIdDuplicateResponses, PostApiV1AgentsData, PostApiV1AgentsErrors, PostApiV1AgentsResponses, PostApiV1ApiKeysData, PostApiV1ApiKeysErrors, PostApiV1ApiKeysResponses, PostApiV1AudioSpeechData, PostApiV1AudioSpeechErrors, PostApiV1AudioSpeechResponses, PostApiV1ChatData, PostApiV1ChatErrors, PostApiV1ChatGenerateReplyData, PostApiV1ChatGenerateReplyErrors, PostApiV1ChatGenerateReplyResponses, PostApiV1ChatGroupsByIdMembersData, PostApiV1ChatGroupsByIdMembersErrors, PostApiV1ChatGroupsByIdMembersResponses, PostApiV1ChatGroupsData, PostApiV1ChatGroupsErrors, PostApiV1ChatGroupsResponses, PostApiV1ChatResponses, PostApiV1ChatTranslateData, PostApiV1ChatTranslateErrors, PostApiV1ChatTranslateResponses, PostApiV1EvalBenchmarksData, PostApiV1EvalBenchmarksErrors, PostApiV1EvalBenchmarksResponses, PostApiV1EvalDatasetsByDatasetIdTestCasesData, PostApiV1EvalDatasetsByDatasetIdTestCasesErrors, PostApiV1EvalDatasetsByDatasetIdTestCasesResponses, PostApiV1EvalDatasetsData, PostApiV1EvalDatasetsErrors, PostApiV1EvalDatasetsResponses, PostApiV1EvalRunsByIdClaimData, PostApiV1EvalRunsByIdClaimErrors, PostApiV1EvalRunsByIdClaimResponses, PostApiV1EvalRunsByIdResultsData, PostApiV1EvalRunsByIdResultsErrors, PostApiV1EvalRunsByIdResultsResponses, PostApiV1EvalRunsByIdRetryErrorsData, PostApiV1EvalRunsByIdRetryErrorsErrors, PostApiV1EvalRunsByIdRetryErrorsResponses, PostApiV1EvalRunsData, PostApiV1EvalRunsErrors, PostApiV1EvalRunsResponses, PostApiV1FilesBatchesData, PostApiV1FilesBatchesErrors, PostApiV1FilesBatchesResponses, PostApiV1FilesByIdChunksData, PostApiV1FilesByIdChunksErrors, PostApiV1FilesByIdChunksResponses, PostApiV1FilesByIdParsesData, PostApiV1FilesByIdParsesErrors, PostApiV1FilesByIdParsesResponses, PostApiV1FilesData, PostApiV1FilesErrors, PostApiV1FilesQueriesData, PostApiV1FilesQueriesErrors, PostApiV1FilesQueriesResponses, PostApiV1FilesResponses, PostApiV1GoalsByIdAdvanceData, PostApiV1GoalsByIdAdvanceErrors, PostApiV1GoalsByIdAdvanceResponses, PostApiV1GoalsByIdPauseData, PostApiV1GoalsByIdPauseErrors, PostApiV1GoalsByIdPauseResponses, PostApiV1GoalsByIdRestartData, PostApiV1GoalsByIdRestartErrors, PostApiV1GoalsByIdRestartResponses, PostApiV1GoalsByIdResumeData, PostApiV1GoalsByIdResumeErrors, PostApiV1GoalsByIdResumeResponses, PostApiV1GoalsData, PostApiV1GoalsErrors, PostApiV1GoalsResponses, PostApiV1ImMessagesData, PostApiV1ImMessagesErrors, PostApiV1ImMessagesResponses, PostApiV1ImTopicsByTopicIdReadData, PostApiV1ImTopicsByTopicIdReadErrors, PostApiV1ImTopicsByTopicIdReadResponses, PostApiV1KnowledgeBasesByIdFilesBatchData, PostApiV1KnowledgeBasesByIdFilesBatchErrors, PostApiV1KnowledgeBasesByIdFilesBatchResponses, PostApiV1KnowledgeBasesByIdFilesMoveData, PostApiV1KnowledgeBasesByIdFilesMoveErrors, PostApiV1KnowledgeBasesByIdFilesMoveResponses, PostApiV1KnowledgeBasesData, PostApiV1KnowledgeBasesErrors, PostApiV1KnowledgeBasesResponses, PostApiV1McpServersByIdSyncData, PostApiV1McpServersByIdSyncErrors, PostApiV1McpServersByIdSyncResponses, PostApiV1McpServersData, PostApiV1McpServersErrors, PostApiV1McpServersResponses, PostApiV1MessagesData, PostApiV1MessagesErrors, PostApiV1MessagesRepliesData, PostApiV1MessagesRepliesErrors, PostApiV1MessagesRepliesResponses, PostApiV1MessagesResponses, PostApiV1MessageTranslationsByMessageIdData, PostApiV1MessageTranslationsByMessageIdErrors, PostApiV1MessageTranslationsByMessageIdResponses, PostApiV1ModelsData, PostApiV1ModelsErrors, PostApiV1ModelsResponses, PostApiV1NotificationsArchiveAllData, PostApiV1NotificationsArchiveAllErrors, PostApiV1NotificationsArchiveAllResponses, PostApiV1NotificationsByIdArchiveData, PostApiV1NotificationsByIdArchiveErrors, PostApiV1NotificationsByIdArchiveResponses, PostApiV1NotificationsReadAllData, PostApiV1NotificationsReadAllErrors, PostApiV1NotificationsReadAllResponses, PostApiV1NotificationsReadData, PostApiV1NotificationsReadErrors, PostApiV1NotificationsReadResponses, PostApiV1PermissionsData, PostApiV1PermissionsErrors, PostApiV1PermissionsResponses, PostApiV1ProvidersData, PostApiV1ProvidersErrors, PostApiV1ProvidersResponses, PostApiV1ResponsesData, PostApiV1ResponsesErrors, PostApiV1ResponsesResponses, PostApiV1RolesData, PostApiV1RolesErrors, PostApiV1RolesResponses, PostApiV1SignalsSourceEventsData, PostApiV1SignalsSourceEventsErrors, PostApiV1SignalsSourceEventsResponses, PostApiV1SignalsTriggerData, PostApiV1SignalsTriggerErrors, PostApiV1SignalsTriggerResponses, PostApiV1TasksByIdRunsData, PostApiV1TasksByIdRunsErrors, PostApiV1TasksByIdRunsResponses, PostApiV1TasksData, PostApiV1TasksErrors, PostApiV1TasksResponses, PostApiV1TopicsData, PostApiV1TopicsErrors, PostApiV1TopicsResponses, PostApiV1UsersData, PostApiV1UsersErrors, PostApiV1UsersResponses, PutApiV1AgentsByIdAccountsByAccountIdCredentialData, PutApiV1AgentsByIdAccountsByAccountIdCredentialErrors, PutApiV1AgentsByIdAccountsByAccountIdCredentialResponses, PutApiV1EvalRunsByRunIdTopicsByTopicIdResultData, PutApiV1EvalRunsByRunIdTopicsByTopicIdResultErrors, PutApiV1EvalRunsByRunIdTopicsByTopicIdResultResponses, PutApiV1PushTokensByDeviceIdData, PutApiV1PushTokensByDeviceIdErrors, PutApiV1PushTokensByDeviceIdResponses } from './types.gen';+import type { DeleteApiV1AgentGroupsByIdData, DeleteApiV1AgentGroupsByIdErrors, DeleteApiV1AgentGroupsByIdResponses, DeleteApiV1AgentsByIdAccountsByAccountIdData, DeleteApiV1AgentsByIdAccountsByAccountIdErrors, DeleteApiV1AgentsByIdAccountsByAccountIdResponses, DeleteApiV1AgentsByIdData, DeleteApiV1AgentsByIdErrors, DeleteApiV1AgentsByIdResponses, DeleteApiV1ApiKeysByIdData, DeleteApiV1ApiKeysByIdErrors, DeleteApiV1ApiKeysByIdResponses, DeleteApiV1ChatGroupsByIdData, DeleteApiV1ChatGroupsByIdErrors, DeleteApiV1ChatGroupsByIdMembersData, DeleteApiV1ChatGroupsByIdMembersErrors, DeleteApiV1ChatGroupsByIdMembersResponses, DeleteApiV1ChatGroupsByIdResponses, DeleteApiV1EvalBenchmarksByIdData, DeleteApiV1EvalBenchmarksByIdErrors, DeleteApiV1EvalBenchmarksByIdResponses, DeleteApiV1EvalDatasetsByIdData, DeleteApiV1EvalDatasetsByIdErrors, DeleteApiV1EvalDatasetsByIdResponses, DeleteApiV1EvalTestCasesByIdData, DeleteApiV1EvalTestCasesByIdErrors, DeleteApiV1EvalTestCasesByIdResponses, DeleteApiV1FilesByIdData, DeleteApiV1FilesByIdErrors, DeleteApiV1FilesByIdResponses, DeleteApiV1GoalsByIdData, DeleteApiV1GoalsByIdErrors, DeleteApiV1GoalsByIdResponses, DeleteApiV1KnowledgeBasesByIdData, DeleteApiV1KnowledgeBasesByIdErrors, DeleteApiV1KnowledgeBasesByIdFilesBatchData, DeleteApiV1KnowledgeBasesByIdFilesBatchErrors, DeleteApiV1KnowledgeBasesByIdFilesBatchResponses, DeleteApiV1KnowledgeBasesByIdResponses, DeleteApiV1McpServersByIdData, DeleteApiV1McpServersByIdErrors, DeleteApiV1McpServersByIdResponses, DeleteApiV1MemoriesByCategoryByIdData, DeleteApiV1MemoriesByCategoryByIdErrors, DeleteApiV1MemoriesByCategoryByIdResponses, DeleteApiV1MemoriesData, DeleteApiV1MemoriesErrors, DeleteApiV1MemoriesResponses, DeleteApiV1MessagesByIdData, DeleteApiV1MessagesByIdErrors, DeleteApiV1MessagesByIdResponses, DeleteApiV1MessagesData, DeleteApiV1MessagesErrors, DeleteApiV1MessagesResponses, DeleteApiV1MessageTranslationsByMessageIdData, DeleteApiV1MessageTranslationsByMessageIdErrors, DeleteApiV1MessageTranslationsByMessageIdResponses, DeleteApiV1PermissionsByIdData, DeleteApiV1PermissionsByIdErrors, DeleteApiV1PermissionsByIdResponses, DeleteApiV1ProvidersByIdData, DeleteApiV1ProvidersByIdErrors, DeleteApiV1ProvidersByIdResponses, DeleteApiV1PushTokensByDeviceIdData, DeleteApiV1PushTokensByDeviceIdErrors, DeleteApiV1PushTokensByDeviceIdResponses, DeleteApiV1RolesByIdData, DeleteApiV1RolesByIdErrors, DeleteApiV1RolesByIdPermissionsData, DeleteApiV1RolesByIdPermissionsErrors, DeleteApiV1RolesByIdPermissionsResponses, DeleteApiV1RolesByIdResponses, DeleteApiV1TasksByIdData, DeleteApiV1TasksByIdErrors, DeleteApiV1TasksByIdResponses, DeleteApiV1TopicsByIdData, DeleteApiV1TopicsByIdErrors, DeleteApiV1TopicsByIdResponses, DeleteApiV1UsersByIdData, DeleteApiV1UsersByIdErrors, DeleteApiV1UsersByIdResponses, DeleteApiV1UsersByIdRolesData, DeleteApiV1UsersByIdRolesErrors, DeleteApiV1UsersByIdRolesResponses, GetApiV1AgentGroupsByIdData, GetApiV1AgentGroupsByIdErrors, GetApiV1AgentGroupsByIdResponses, GetApiV1AgentGroupsData, GetApiV1AgentGroupsErrors, GetApiV1AgentGroupsResponses, GetApiV1AgentsByIdAccountsByAccountIdData, GetApiV1AgentsByIdAccountsByAccountIdErrors, GetApiV1AgentsByIdAccountsByAccountIdResponses, GetApiV1AgentsByIdAccountsData, GetApiV1AgentsByIdAccountsErrors, GetApiV1AgentsByIdAccountsResponses, GetApiV1AgentsByIdData, GetApiV1AgentsByIdErrors, GetApiV1AgentsByIdResponses, GetApiV1AgentsData, GetApiV1AgentsErrors, GetApiV1AgentsResponses, GetApiV1ApiKeysByIdData, GetApiV1ApiKeysByIdErrors, GetApiV1ApiKeysByIdResponses, GetApiV1ApiKeysData, GetApiV1ApiKeysErrors, GetApiV1ApiKeysResponses, GetApiV1ChatGroupsByIdData, GetApiV1ChatGroupsByIdErrors, GetApiV1ChatGroupsByIdResponses, GetApiV1ChatGroupsData, GetApiV1ChatGroupsErrors, GetApiV1ChatGroupsResponses, GetApiV1DocumentsByIdData, GetApiV1DocumentsByIdErrors, GetApiV1DocumentsByIdResponses, GetApiV1DocumentsData, GetApiV1DocumentsErrors, GetApiV1DocumentsResponses, GetApiV1EvalBenchmarksByIdData, GetApiV1EvalBenchmarksByIdErrors, GetApiV1EvalBenchmarksByIdResponses, GetApiV1EvalBenchmarksData, GetApiV1EvalBenchmarksErrors, GetApiV1EvalBenchmarksResponses, GetApiV1EvalDatasetsByDatasetIdTestCasesData, GetApiV1EvalDatasetsByDatasetIdTestCasesErrors, GetApiV1EvalDatasetsByDatasetIdTestCasesResponses, GetApiV1EvalDatasetsByIdData, GetApiV1EvalDatasetsByIdErrors, GetApiV1EvalDatasetsByIdResponses, GetApiV1EvalDatasetsData, GetApiV1EvalDatasetsErrors, GetApiV1EvalDatasetsResponses, GetApiV1EvalRunsByIdData, GetApiV1EvalRunsByIdErrors, GetApiV1EvalRunsByIdResponses, GetApiV1EvalRunsByIdResultsData, GetApiV1EvalRunsByIdResultsErrors, GetApiV1EvalRunsByIdResultsResponses, GetApiV1EvalRunsByIdTopicsData, GetApiV1EvalRunsByIdTopicsErrors, GetApiV1EvalRunsByIdTopicsResponses, GetApiV1EvalRunsData, GetApiV1EvalRunsErrors, GetApiV1EvalRunsResponses, GetApiV1EvalTestCasesByIdData, GetApiV1EvalTestCasesByIdErrors, GetApiV1EvalTestCasesByIdResponses, GetApiV1FilesByIdChunksData, GetApiV1FilesByIdChunksErrors, GetApiV1FilesByIdChunksResponses, GetApiV1FilesByIdData, GetApiV1FilesByIdErrors, GetApiV1FilesByIdResponses, GetApiV1FilesByIdUrlData, GetApiV1FilesByIdUrlErrors, GetApiV1FilesByIdUrlResponses, GetApiV1FilesData, GetApiV1FilesErrors, GetApiV1FilesResponses, GetApiV1GoalsByIdData, GetApiV1GoalsByIdErrors, GetApiV1GoalsByIdResponses, GetApiV1GoalsByIdSupervisionData, GetApiV1GoalsByIdSupervisionErrors, GetApiV1GoalsByIdSupervisionResponses, GetApiV1GoalsData, GetApiV1GoalsErrors, GetApiV1GoalsResponses, GetApiV1HealthData, GetApiV1HealthResponses, GetApiV1ImTopicsByTopicIdSyncData, GetApiV1ImTopicsByTopicIdSyncErrors, GetApiV1ImTopicsByTopicIdSyncResponses, GetApiV1KnowledgeBasesByIdData, GetApiV1KnowledgeBasesByIdErrors, GetApiV1KnowledgeBasesByIdFilesData, GetApiV1KnowledgeBasesByIdFilesErrors, GetApiV1KnowledgeBasesByIdFilesResponses, GetApiV1KnowledgeBasesByIdResponses, GetApiV1KnowledgeBasesData, GetApiV1KnowledgeBasesErrors, GetApiV1KnowledgeBasesResponses, GetApiV1McpServersByIdData, GetApiV1McpServersByIdErrors, GetApiV1McpServersByIdResponses, GetApiV1McpServersData, GetApiV1McpServersErrors, GetApiV1McpServersResponses, GetApiV1MemoriesByCategoryData, GetApiV1MemoriesByCategoryErrors, GetApiV1MemoriesByCategoryResponses, GetApiV1MemoriesPersonaData, GetApiV1MemoriesPersonaErrors, GetApiV1MemoriesPersonaResponses, GetApiV1MemoriesPersonaVersionsData, GetApiV1MemoriesPersonaVersionsErrors, GetApiV1MemoriesPersonaVersionsResponses, GetApiV1MessagesByIdData, GetApiV1MessagesByIdErrors, GetApiV1MessagesByIdResponses, GetApiV1MessagesCountData, GetApiV1MessagesCountErrors, GetApiV1MessagesCountResponses, GetApiV1MessagesData, GetApiV1MessagesErrors, GetApiV1MessagesResponses, GetApiV1MessageTranslationsByMessageIdData, GetApiV1MessageTranslationsByMessageIdErrors, GetApiV1MessageTranslationsByMessageIdResponses, GetApiV1ModelsByProviderIdByModelIdData, GetApiV1ModelsByProviderIdByModelIdErrors, GetApiV1ModelsByProviderIdByModelIdResponses, GetApiV1ModelsData, GetApiV1ModelsErrors, GetApiV1ModelsResponses, GetApiV1NotificationsCountsData, GetApiV1NotificationsCountsErrors, GetApiV1NotificationsCountsResponses, GetApiV1NotificationsData, GetApiV1NotificationsErrors, GetApiV1NotificationsResponses, GetApiV1NotificationsSettingsData, GetApiV1NotificationsSettingsErrors, GetApiV1NotificationsSettingsResponses, GetApiV1NotificationsUnreadCountData, GetApiV1NotificationsUnreadCountErrors, GetApiV1NotificationsUnreadCountResponses, GetApiV1PermissionsByIdData, GetApiV1PermissionsByIdErrors, GetApiV1PermissionsByIdResponses, GetApiV1PermissionsData, GetApiV1PermissionsErrors, GetApiV1PermissionsResponses, GetApiV1PluginsData, GetApiV1PluginsErrors, GetApiV1PluginsResponses, GetApiV1ProvidersByIdData, GetApiV1ProvidersByIdErrors, GetApiV1ProvidersByIdResponses, GetApiV1ProvidersData, GetApiV1ProvidersErrors, GetApiV1ProvidersResponses, GetApiV1RolesByIdData, GetApiV1RolesByIdErrors, GetApiV1RolesByIdPermissionsData, GetApiV1RolesByIdPermissionsErrors, GetApiV1RolesByIdPermissionsResponses, GetApiV1RolesByIdResponses, GetApiV1RolesData, GetApiV1RolesErrors, GetApiV1RolesResponses, GetApiV1SignalsReceiptsData, GetApiV1SignalsReceiptsErrors, GetApiV1SignalsReceiptsResponses, GetApiV1TasksByIdData, GetApiV1TasksByIdErrors, GetApiV1TasksByIdResponses, GetApiV1TasksByIdRunsData, GetApiV1TasksByIdRunsErrors, GetApiV1TasksByIdRunsResponses, GetApiV1TasksData, GetApiV1TasksErrors, GetApiV1TasksResponses, GetApiV1TopicsByIdData, GetApiV1TopicsByIdErrors, GetApiV1TopicsByIdResponses, GetApiV1TopicsByTopicIdThreadsData, GetApiV1TopicsByTopicIdThreadsErrors, GetApiV1TopicsByTopicIdThreadsResponses, GetApiV1TopicsData, GetApiV1TopicsErrors, GetApiV1TopicsResponses, GetApiV1UsageData, GetApiV1UsageErrors, GetApiV1UsageResponses, GetApiV1UsersByIdData, GetApiV1UsersByIdErrors, GetApiV1UsersByIdResponses, GetApiV1UsersByIdRolesData, GetApiV1UsersByIdRolesErrors, GetApiV1UsersByIdRolesResponses, GetApiV1UsersData, GetApiV1UsersErrors, GetApiV1UsersMeData, GetApiV1UsersMeErrors, GetApiV1UsersMeResponses, GetApiV1UsersResponses, PatchApiV1AgentGroupsByIdData, PatchApiV1AgentGroupsByIdErrors, PatchApiV1AgentGroupsByIdResponses, PatchApiV1AgentsByIdAccountsByAccountIdData, PatchApiV1AgentsByIdAccountsByAccountIdErrors, PatchApiV1AgentsByIdAccountsByAccountIdResponses, PatchApiV1AgentsByIdData, PatchApiV1AgentsByIdErrors, PatchApiV1AgentsByIdResponses, PatchApiV1ApiKeysByIdData, PatchApiV1ApiKeysByIdErrors, PatchApiV1ApiKeysByIdResponses, PatchApiV1ChatGroupsByIdData, PatchApiV1ChatGroupsByIdErrors, PatchApiV1ChatGroupsByIdResponses, PatchApiV1DocumentsByIdData, PatchApiV1DocumentsByIdErrors, PatchApiV1DocumentsByIdResponses, PatchApiV1EvalBenchmarksByIdData, PatchApiV1EvalBenchmarksByIdErrors, PatchApiV1EvalBenchmarksByIdResponses, PatchApiV1EvalDatasetsByIdData, PatchApiV1EvalDatasetsByIdErrors, PatchApiV1EvalDatasetsByIdResponses, PatchApiV1EvalRunsByIdStatusData, PatchApiV1EvalRunsByIdStatusErrors, PatchApiV1EvalRunsByIdStatusResponses, PatchApiV1EvalTestCasesByIdData, PatchApiV1EvalTestCasesByIdErrors, PatchApiV1EvalTestCasesByIdResponses, PatchApiV1FilesByIdData, PatchApiV1FilesByIdErrors, PatchApiV1FilesByIdResponses, PatchApiV1GoalsByIdData, PatchApiV1GoalsByIdErrors, PatchApiV1GoalsByIdResponses, PatchApiV1KnowledgeBasesByIdData, PatchApiV1KnowledgeBasesByIdErrors, PatchApiV1KnowledgeBasesByIdResponses, PatchApiV1McpServersByIdData, PatchApiV1McpServersByIdErrors, PatchApiV1McpServersByIdResponses, PatchApiV1MessageTranslationsByMessageIdData, PatchApiV1MessageTranslationsByMessageIdErrors, PatchApiV1MessageTranslationsByMessageIdResponses, PatchApiV1ModelsByProviderIdByModelIdData, PatchApiV1ModelsByProviderIdByModelIdErrors, PatchApiV1ModelsByProviderIdByModelIdResponses, PatchApiV1NotificationsSettingsData, PatchApiV1NotificationsSettingsErrors, PatchApiV1NotificationsSettingsResponses, PatchApiV1PermissionsByIdData, PatchApiV1PermissionsByIdErrors, PatchApiV1PermissionsByIdResponses, PatchApiV1ProvidersByIdData, PatchApiV1ProvidersByIdErrors, PatchApiV1ProvidersByIdResponses, PatchApiV1RolesByIdData, PatchApiV1RolesByIdErrors, PatchApiV1RolesByIdPermissionsData, PatchApiV1RolesByIdPermissionsErrors, PatchApiV1RolesByIdPermissionsResponses, PatchApiV1RolesByIdResponses, PatchApiV1TasksByIdData, PatchApiV1TasksByIdErrors, PatchApiV1TasksByIdResponses, PatchApiV1TasksByIdStatusData, PatchApiV1TasksByIdStatusErrors, PatchApiV1TasksByIdStatusResponses, PatchApiV1TopicsByIdData, PatchApiV1TopicsByIdErrors, PatchApiV1TopicsByIdResponses, PatchApiV1UsersByIdData, PatchApiV1UsersByIdErrors, PatchApiV1UsersByIdResponses, PatchApiV1UsersByIdRolesData, PatchApiV1UsersByIdRolesErrors, PatchApiV1UsersByIdRolesResponses, PostApiV1AgentGroupsData, PostApiV1AgentGroupsErrors, PostApiV1AgentGroupsResponses, PostApiV1AgentsByIdAccountsData, PostApiV1AgentsByIdAccountsErrors, PostApiV1AgentsByIdAccountsResponses, PostApiV1AgentsByIdDuplicateData, PostApiV1AgentsByIdDuplicateErrors, PostApiV1AgentsByIdDuplicateResponses, PostApiV1AgentsData, PostApiV1AgentsErrors, PostApiV1AgentsResponses, PostApiV1ApiKeysData, PostApiV1ApiKeysErrors, PostApiV1ApiKeysResponses, PostApiV1AudioSpeechData, PostApiV1AudioSpeechErrors, PostApiV1AudioSpeechResponses, PostApiV1ChatData, PostApiV1ChatErrors, PostApiV1ChatGenerateReplyData, PostApiV1ChatGenerateReplyErrors, PostApiV1ChatGenerateReplyResponses, PostApiV1ChatGroupsByIdMembersData, PostApiV1ChatGroupsByIdMembersErrors, PostApiV1ChatGroupsByIdMembersResponses, PostApiV1ChatGroupsData, PostApiV1ChatGroupsErrors, PostApiV1ChatGroupsResponses, PostApiV1ChatResponses, PostApiV1ChatTranslateData, PostApiV1ChatTranslateErrors, PostApiV1ChatTranslateResponses, PostApiV1DocumentsData, PostApiV1DocumentsErrors, PostApiV1DocumentsResponses, PostApiV1EvalBenchmarksData, PostApiV1EvalBenchmarksErrors, PostApiV1EvalBenchmarksResponses, PostApiV1EvalDatasetsByDatasetIdTestCasesData, PostApiV1EvalDatasetsByDatasetIdTestCasesErrors, PostApiV1EvalDatasetsByDatasetIdTestCasesResponses, PostApiV1EvalDatasetsData, PostApiV1EvalDatasetsErrors, PostApiV1EvalDatasetsResponses, PostApiV1EvalRunsByIdClaimData, PostApiV1EvalRunsByIdClaimErrors, PostApiV1EvalRunsByIdClaimResponses, PostApiV1EvalRunsByIdResultsData, PostApiV1EvalRunsByIdResultsErrors, PostApiV1EvalRunsByIdResultsResponses, PostApiV1EvalRunsByIdRetryErrorsData, PostApiV1EvalRunsByIdRetryErrorsErrors, PostApiV1EvalRunsByIdRetryErrorsResponses, PostApiV1EvalRunsData, PostApiV1EvalRunsErrors, PostApiV1EvalRunsResponses, PostApiV1FilesBatchesData, PostApiV1FilesBatchesErrors, PostApiV1FilesBatchesResponses, PostApiV1FilesByIdChunksData, PostApiV1FilesByIdChunksErrors, PostApiV1FilesByIdChunksResponses, PostApiV1FilesByIdParsesData, PostApiV1FilesByIdParsesErrors, PostApiV1FilesByIdParsesResponses, PostApiV1FilesData, PostApiV1FilesErrors, PostApiV1FilesQueriesData, PostApiV1FilesQueriesErrors, PostApiV1FilesQueriesResponses, PostApiV1FilesResponses, PostApiV1GoalsByIdAdvanceData, PostApiV1GoalsByIdAdvanceErrors, PostApiV1GoalsByIdAdvanceResponses, PostApiV1GoalsByIdPauseData, PostApiV1GoalsByIdPauseErrors, PostApiV1GoalsByIdPauseResponses, PostApiV1GoalsByIdRestartData, PostApiV1GoalsByIdRestartErrors, PostApiV1GoalsByIdRestartResponses, PostApiV1GoalsByIdResumeData, PostApiV1GoalsByIdResumeErrors, PostApiV1GoalsByIdResumeResponses, PostApiV1GoalsData, PostApiV1GoalsErrors, PostApiV1GoalsResponses, PostApiV1ImMessagesData, PostApiV1ImMessagesErrors, PostApiV1ImMessagesResponses, PostApiV1ImTopicsByTopicIdReadData, PostApiV1ImTopicsByTopicIdReadErrors, PostApiV1ImTopicsByTopicIdReadResponses, PostApiV1KnowledgeBasesByIdFilesBatchData, PostApiV1KnowledgeBasesByIdFilesBatchErrors, PostApiV1KnowledgeBasesByIdFilesBatchResponses, PostApiV1KnowledgeBasesByIdFilesMoveData, PostApiV1KnowledgeBasesByIdFilesMoveErrors, PostApiV1KnowledgeBasesByIdFilesMoveResponses, PostApiV1KnowledgeBasesData, PostApiV1KnowledgeBasesErrors, PostApiV1KnowledgeBasesResponses, PostApiV1McpServersByIdSyncData, PostApiV1McpServersByIdSyncErrors, PostApiV1McpServersByIdSyncResponses, PostApiV1McpServersData, PostApiV1McpServersErrors, PostApiV1McpServersResponses, PostApiV1MessagesData, PostApiV1MessagesErrors, PostApiV1MessagesRepliesData, PostApiV1MessagesRepliesErrors, PostApiV1MessagesRepliesResponses, PostApiV1MessagesResponses, PostApiV1MessageTranslationsByMessageIdData, PostApiV1MessageTranslationsByMessageIdErrors, PostApiV1MessageTranslationsByMessageIdResponses, PostApiV1ModelsData, PostApiV1ModelsErrors, PostApiV1ModelsResponses, PostApiV1NotificationsArchiveAllData, PostApiV1NotificationsArchiveAllErrors, PostApiV1NotificationsArchiveAllResponses, PostApiV1NotificationsByIdArchiveData, PostApiV1NotificationsByIdArchiveErrors, PostApiV1NotificationsByIdArchiveResponses, PostApiV1NotificationsReadAllData, PostApiV1NotificationsReadAllErrors, PostApiV1NotificationsReadAllResponses, PostApiV1NotificationsReadData, PostApiV1NotificationsReadErrors, PostApiV1NotificationsReadResponses, PostApiV1PermissionsData, PostApiV1PermissionsErrors, PostApiV1PermissionsResponses, PostApiV1ProvidersData, PostApiV1ProvidersErrors, PostApiV1ProvidersResponses, PostApiV1ResponsesData, PostApiV1ResponsesErrors, PostApiV1ResponsesResponses, PostApiV1RolesData, PostApiV1RolesErrors, PostApiV1RolesResponses, PostApiV1SignalsSourceEventsData, PostApiV1SignalsSourceEventsErrors, PostApiV1SignalsSourceEventsResponses, PostApiV1SignalsTriggerData, PostApiV1SignalsTriggerErrors, PostApiV1SignalsTriggerResponses, PostApiV1TasksByIdRunsData, PostApiV1TasksByIdRunsErrors, PostApiV1TasksByIdRunsResponses, PostApiV1TasksData, PostApiV1TasksErrors, PostApiV1TasksResponses, PostApiV1TopicsData, PostApiV1TopicsErrors, PostApiV1TopicsResponses, PostApiV1UsersData, PostApiV1UsersErrors, PostApiV1UsersResponses, PutApiV1AgentsByIdAccountsByAccountIdCredentialData, PutApiV1AgentsByIdAccountsByAccountIdCredentialErrors, PutApiV1AgentsByIdAccountsByAccountIdCredentialResponses, PutApiV1EvalRunsByRunIdTopicsByTopicIdResultData, PutApiV1EvalRunsByRunIdTopicsByTopicIdResultErrors, PutApiV1EvalRunsByRunIdTopicsByTopicIdResultResponses, PutApiV1PushTokensByDeviceIdData, PutApiV1PushTokensByDeviceIdErrors, PutApiV1PushTokensByDeviceIdResponses } from './types.gen';const mergeMethodHeaders = (defaults: Record<string, unknown>,@@ -476,6 +476,58 @@ export class ChatGroups extends HeyApiClient {}}+export class Documents extends HeyApiClient {+ /**+ * List documents+ */+ public list<ThrowOnError extends boolean = false>(options?: Options<GetApiV1DocumentsData, ThrowOnError>): RequestResult<GetApiV1DocumentsResponses, GetApiV1DocumentsErrors, ThrowOnError> {+ return (options?.client ?? this.client).get<GetApiV1DocumentsResponses, GetApiV1DocumentsErrors, ThrowOnError>({+ security: [{ scheme: 'bearer', type: 'http' }],+ url: '/api/v1/documents',+ ...options+ });+ }++ /**+ * Create a document+ *+ * Creates a page from Markdown, or a folder with `fileType: "custom/folder"`.+ */+ public create<ThrowOnError extends boolean = false>(options: Options<PostApiV1DocumentsData, ThrowOnError>): RequestResult<PostApiV1DocumentsResponses, PostApiV1DocumentsErrors, ThrowOnError> {+ return (options.client ?? this.client).post<PostApiV1DocumentsResponses, PostApiV1DocumentsErrors, ThrowOnError>({+ security: [{ scheme: 'bearer', type: 'http' }],+ url: '/api/v1/documents',+ ...options,+ headers: mergeMethodHeaders({ 'Content-Type': 'application/json' }, options.headers)+ });+ }++ /**+ * Get a document+ */+ public get<ThrowOnError extends boolean = false>(options: Options<GetApiV1DocumentsByIdData, ThrowOnError>): RequestResult<GetApiV1DocumentsByIdResponses, GetApiV1DocumentsByIdErrors, ThrowOnError> {+ return (options.client ?? this.client).get<GetApiV1DocumentsByIdResponses, GetApiV1DocumentsByIdErrors, ThrowOnError>({+ security: [{ scheme: 'bearer', type: 'http' }],+ url: '/api/v1/documents/{id}',+ ...options+ });+ }++ /**+ * Update a document+ *+ * Replaces the title and/or the whole Markdown body. A page open in the editor receives the write through its live room.+ */+ public update<ThrowOnError extends boolean = false>(options: Options<PatchApiV1DocumentsByIdData, ThrowOnError>): RequestResult<PatchApiV1DocumentsByIdResponses, PatchApiV1DocumentsByIdErrors, ThrowOnError> {+ return (options.client ?? this.client).patch<PatchApiV1DocumentsByIdResponses, PatchApiV1DocumentsByIdErrors, ThrowOnError>({+ security: [{ scheme: 'bearer', type: 'http' }],+ url: '/api/v1/documents/{id}',+ ...options,+ headers: mergeMethodHeaders({ 'Content-Type': 'application/json' }, options.headers)+ });+ }+}+export class Eval extends HeyApiClient {/*** List eval runs@@ -2276,6 +2328,11 @@ export class LobeHub extends HeyApiClient {return this._chatGroups ??= new ChatGroups({ client: this.client });}+ private _documents?: Documents;+ get documents(): Documents {+ return this._documents ??= new Documents({ client: this.client });+ }+private _eval?: Eval;get eval(): Eval {return this._eval ??= new Eval({ client: this.client });diff --git a/packages/sdk/src/generated/types.gen.ts b/packages/sdk/src/generated/types.gen.tsindex 77d5599bf61..b8ca2ce203e 100644--- a/packages/sdk/src/generated/types.gen.ts+++ b/packages/sdk/src/generated/types.gen.ts@@ -288,6 +288,30 @@ export type ChatGroupMember = {role: 'supervisor' | 'participant' | 'assistant' | null;};+export type DocumentSummary = {+ createdAt: string;+ fileType: string;+ id: string;+ parentId: string | null;+ slug: string | null;+ title: string | null;+ updatedAt: string;+};++export type Document = {+ createdAt: string;+ fileType: string;+ id: string;+ parentId: string | null;+ slug: string | null;+ title: string | null;+ updatedAt: string;+ /**+ * Markdown body.+ */+ content: string | null;+};+export type EvalRun = {config: {caseSelection?: {@@ -1030,10 +1054,10 @@ export type GoalGraphWorkVersionLink = {identifier: string | null;mimeType?: string;resourceId: string | null;- resourceType?: 'canvas' | 'document' | 'github_issue' | 'github_pull_request' | 'linear_document' | 'linear_issue' | 'file' | 'goal_report' | 'task';+ resourceType?: 'canvas' | 'document' | 'github_issue' | 'github_pull_request' | 'linear_document' | 'linear_issue' | 'link' | 'file' | 'collection' | 'goal_report' | 'task';status: string | null;title: string | null;- type: 'canvas' | 'document' | 'external' | 'file' | 'goal_report' | 'task';+ type: 'canvas' | 'document' | 'external' | 'file' | 'collection' | 'goal_report' | 'task';url: string | null;workId: string;};@@ -4815,6 +4839,250 @@ export type PostApiV1ChatGroupsByIdMembersResponses = {export type PostApiV1ChatGroupsByIdMembersResponse = PostApiV1ChatGroupsByIdMembersResponses[keyof PostApiV1ChatGroupsByIdMembersResponses];+export type GetApiV1DocumentsData = {+ body?: never;+ path?: never;+ query?: {+ /**+ * Opaque cursor from the previous page's `nextCursor`. Omit for the first page.+ */+ cursor?: string;+ /**+ * Page size, 1–100. Defaults to 20.+ */+ limit?: number;+ /**+ * Only list the direct children of this folder (id or slug).+ */+ parentId?: string;+ };+ url: '/api/v1/documents';+};++export type GetApiV1DocumentsErrors = {+ /**+ * Invalid request+ */+ 400: ApiError;+ /**+ * Authentication required+ */+ 401: ApiError;+ /**+ * Insufficient permission+ */+ 403: ApiError;+ /**+ * Rate limit exceeded+ */+ 429: ApiError;+ /**+ * Internal server error+ */+ 500: ApiError;+};++export type GetApiV1DocumentsError = GetApiV1DocumentsErrors[keyof GetApiV1DocumentsErrors];++export type GetApiV1DocumentsResponses = {+ /**+ * Successful response+ */+ 200: {+ data: {+ items: Array<DocumentSummary>;+ hasMore: PageHasMore;+ nextCursor: PageNextCursor;+ total: PageTotal;+ };+ message?: string;+ success: true;+ timestamp: string;+ };+};++export type GetApiV1DocumentsResponse = GetApiV1DocumentsResponses[keyof GetApiV1DocumentsResponses];++export type PostApiV1DocumentsData = {+ body: {+ /**+ * Markdown body. Omit for a folder.+ */+ content?: string;+ /**+ * `custom/folder` creates a folder; defaults to a page (`custom/document`).+ */+ fileType?: string;+ /**+ * Folder to create in (id or slug).+ */+ parentId?: string;+ title: string;+ };+ headers?: {+ /**+ * Makes the request safe to retry: the first request with a key runs, and repeats with the same key and the same request within 24 hours get its stored response back (with `Idempotent-Replayed: true`). A repeat while the first is still running answers 409, and reusing a key for a different request (method, path or body) answers 422 (both `idempotency_conflict`). Server errors, 429s and streamed responses are not stored. Keys are scoped to the authenticated user, the credential (API key) and the resolved workspace. A request still running after 5 minutes releases its in-flight claim, after which a retry with the same key runs again.+ */+ 'Idempotency-Key'?: string;+ };+ path?: never;+ query?: never;+ url: '/api/v1/documents';+};++export type PostApiV1DocumentsErrors = {+ /**+ * Invalid request+ */+ 400: ApiError;+ /**+ * Authentication required+ */+ 401: ApiError;+ /**+ * Insufficient permission+ */+ 403: ApiError;+ /**+ * Resource not found+ */+ 404: ApiError;+ /**+ * Rate limit exceeded+ */+ 429: ApiError;+ /**+ * Internal server error+ */+ 500: ApiError;+};++export type PostApiV1DocumentsError = PostApiV1DocumentsErrors[keyof PostApiV1DocumentsErrors];++export type PostApiV1DocumentsResponses = {+ /**+ * Successful response+ */+ 201: {+ data: Document;+ message?: string;+ success: true;+ timestamp: string;+ };+};++export type PostApiV1DocumentsResponse = PostApiV1DocumentsResponses[keyof PostApiV1DocumentsResponses];++export type GetApiV1DocumentsByIdData = {+ body?: never;+ path: {+ id: string;+ };+ query?: never;+ url: '/api/v1/documents/{id}';+};++export type GetApiV1DocumentsByIdErrors = {+ /**+ * Invalid request+ */+ 400: ApiError;+ /**+ * Authentication required+ */+ 401: ApiError;+ /**+ * Insufficient permission+ */+ 403: ApiError;+ /**+ * Resource not found+ */+ 404: ApiError;+ /**+ * Rate limit exceeded+ */+ 429: ApiError;+ /**+ * Internal server error+ */+ 500: ApiError;+};++export type GetApiV1DocumentsByIdError = GetApiV1DocumentsByIdErrors[keyof GetApiV1DocumentsByIdErrors];++export type GetApiV1DocumentsByIdResponses = {+ /**+ * Successful response+ */+ 200: {+ data: Document;+ message?: string;+ success: true;+ timestamp: string;+ };+};++export type GetApiV1DocumentsByIdResponse = GetApiV1DocumentsByIdResponses[keyof GetApiV1DocumentsByIdResponses];++export type PatchApiV1DocumentsByIdData = {+ body: {+ /**+ * Markdown body; replaces the whole body.+ */+ content?: string;+ title?: string;+ };+ path: {+ id: string;+ };+ query?: never;+ url: '/api/v1/documents/{id}';+};++export type PatchApiV1DocumentsByIdErrors = {+ /**+ * Invalid request+ */+ 400: ApiError;+ /**+ * Authentication required+ */+ 401: ApiError;+ /**+ * Insufficient permission+ */+ 403: ApiError;+ /**+ * Resource not found+ */+ 404: ApiError;+ /**+ * Rate limit exceeded+ */+ 429: ApiError;+ /**+ * Internal server error+ */+ 500: ApiError;+};++export type PatchApiV1DocumentsByIdError = PatchApiV1DocumentsByIdErrors[keyof PatchApiV1DocumentsByIdErrors];++export type PatchApiV1DocumentsByIdResponses = {+ /**+ * Successful response+ */+ 200: {+ data: Document;+ message?: string;+ success: true;+ timestamp: string;+ };+};++export type PatchApiV1DocumentsByIdResponse = PatchApiV1DocumentsByIdResponses[keyof PatchApiV1DocumentsByIdResponses];+export type GetApiV1EvalRunsData = {body?: never;path?: never;diff --git a/packages/trpc/src/utils/__tests__/internalJwt.test.ts b/packages/trpc/src/utils/__tests__/internalJwt.test.tsindex 1601997356d..46cae65dba3 100644--- a/packages/trpc/src/utils/__tests__/internalJwt.test.ts+++ b/packages/trpc/src/utils/__tests__/internalJwt.test.ts@@ -230,6 +230,12 @@ describe('internalJwt', () => {expect(validateHeteroOperationClaims(claims)).toEqual(claims);});+ it('accepts the capability every run carries to register its own Works', async () => {+ const { validateHeteroOperationClaims } = await import('../internalJwt');+ const claims = { ...validClaims, capabilities: ['hetero:ingest', 'work:write'] };+ expect(validateHeteroOperationClaims(claims)).toEqual(claims);+ });+it('rejects a capability it does not know', async () => {const { validateHeteroOperationClaims } = await import('../internalJwt');expect(diff --git a/packages/trpc/src/utils/internalJwt.ts b/packages/trpc/src/utils/internalJwt.tsindex 1df3adc7b5b..8efa25085db 100644--- a/packages/trpc/src/utils/internalJwt.ts+++ b/packages/trpc/src/utils/internalJwt.ts@@ -34,7 +34,8 @@ export type HeteroOperationCapability =| 'hetero:finish'| 'hetero:ingest'| 'hetero:intervention:read'- | 'model:invoke';+ | 'model:invoke'+ | 'work:write';export interface HeteroOperationJwtClaims {aud: typeof HETERO_OPERATION_JWT_AUDIENCE;@@ -239,6 +240,7 @@ export const validateHeteroOperationClaims = ('hetero:ingest','hetero:finish','hetero:intervention:read',+ 'work:write',].includes(capability as string),) ||(payload.model !== undefined && typeof payload.model !== 'string') ||diff --git a/packages/types/src/agent/share.ts b/packages/types/src/agent/share.tsindex 4ad5304f877..76122a98ea8 100644--- a/packages/types/src/agent/share.ts+++ b/packages/types/src/agent/share.ts@@ -1,5 +1,5 @@import type { ShareVisibility } from '../topic';-import type { WorkItem } from '../work';+import type { CollectionWorkVersionMetadata, WorkItem } from '../work';/** A creator-authored visitor task, independent of the agent's opening questions. */export interface AgentShareDemoCase {@@ -21,7 +21,11 @@ export type SharedAgentWork = Pick<| 'type'| 'updatedAt'| 'url'-> & { totalCost: number | null };+> & {+ /** A collection Work's images, so its card shows the count and opens the grid; `url` is the cover. */+ collection?: CollectionWorkVersionMetadata;+ totalCost: number | null;+};/** Creator-side delivery aggregates; selection for the showcase does not change the sample. */export interface SharedAgentDeliveryStats {diff --git a/packages/types/src/tool/builtin.ts b/packages/types/src/tool/builtin.tsindex bbbca8a51c5..bacd659c3db 100644--- a/packages/types/src/tool/builtin.ts+++ b/packages/types/src/tool/builtin.ts@@ -3,10 +3,12 @@ import { z } from 'zod';import { type DeviceUnavailableErrorData } from '../device';import { type RuntimeStepContext } from '../stepContext';+import { type PluginApiWorkConfig, PluginApiWorkConfigSchema } from './builtinWork';import { type HumanInterventionConfig, type HumanInterventionPolicy } from './intervention';import { HumanInterventionConfigSchema, HumanInterventionPolicySchema } from './intervention';export * from './builtinIntervention';+export * from './builtinWork';export interface Meta {/**@@ -135,42 +137,6 @@ export const ExtendedHumanInterventionConfigSchema = z.union([z.object({ dynamic: DynamicInterventionConfigSchema }),]);-/**- * Lifecycle action a tool API performs on its Work resource. Drives the Work- * version `role` (`create`/`update` → `created`/`updated`) and, for `delete`,- * routes to the resource's delete path instead of a version upsert.- */-export type PluginApiWorkAction = 'create' | 'delete' | 'update';--/**- * The Work resource kind an API produces. Selects the framework-side identity- * extractor and the `WorkModel` register method used by the dispatch layer.- */-export type PluginApiWorkResourceType = 'document' | 'task';--/**- * Declarative Work-registration config on a builtin tool API.- *- * Presence of this field is the single source of truth for "this API produces a- * Work". The tool-execution dispatch layers (server `BuiltinToolsExecutor` /- * client `invokeExecutor`) read it after a successful call, extract the resource- * identity from the result/args, and register the Work version — so tools need- * zero imperative registration code.- *- * Like `humanIntervention`, this is framework-only config: the model tools- * schema conversion only reads `name`/`description`/`parameters`, so `work`- * never leaks into the LLM-facing tool spec.- */-export interface PluginApiWorkConfig {- action: PluginApiWorkAction;- resourceType: PluginApiWorkResourceType;-}--export const PluginApiWorkConfigSchema = z.object({- action: z.enum(['create', 'update', 'delete']),- resourceType: z.enum(['document', 'task']),-});-export interface LobeChatPluginApi {/*** Default execution timeout in milliseconds for this API.diff --git a/packages/types/src/tool/builtinWork.ts b/packages/types/src/tool/builtinWork.tsnew file mode 100644index 00000000000..7b0459b143f--- /dev/null+++ b/packages/types/src/tool/builtinWork.ts@@ -0,0 +1,53 @@+import { z } from 'zod';++/**+ * Lifecycle action a tool API performs on its Work resource. Drives the Work+ * version `role` (`create`/`update` → `created`/`updated`) and, for `delete`,+ * routes to the resource's delete path instead of a version upsert.+ */+export type PluginApiWorkAction = 'create' | 'delete' | 'update';++/**+ * The Work resource kind an API produces. Selects the framework-side identity+ * extractor and the `WorkModel` register method used by the dispatch layer.+ */+export type PluginApiWorkResourceType = 'document' | 'task';++/**+ * Declarative Work-registration config on a builtin tool API.+ *+ * Presence of this field is the single source of truth for "this API produces a+ * Work". The tool-execution dispatch layers (server `BuiltinToolsExecutor` /+ * client `invokeExecutor`) read it after a successful call, extract the resource+ * identity from the result/args, and register the Work version — so tools need+ * zero imperative registration code.+ *+ * Like `humanIntervention`, this is framework-only config: the model tools+ * schema conversion only reads `name`/`description`/`parameters`, so `work`+ * never leaks into the LLM-facing tool spec.+ */+export interface PluginApiWorkConfig {+ action: PluginApiWorkAction;+ /**+ * Mark the Works this API creates as agent-written. Defaults to false: an+ * automatically collected Work stays read-only to the agent. Applied only+ * when the call creates the Work identity; editability never changes+ * afterwards.+ *+ * `lh work update` / `delete` and the `lobe-work` tool change only file, link+ * and collection Works, so on the document and task Works this API creates+ * the flag records intent for a future policy and grants nothing today.+ *+ * Field-level policy for the agent belongs on this config too, so a future+ * system-owned field (for example a price) is declared here rather than+ * special-cased in each write path.+ */+ agentEditable?: boolean;+ resourceType: PluginApiWorkResourceType;+}++export const PluginApiWorkConfigSchema = z.object({+ action: z.enum(['create', 'update', 'delete']),+ agentEditable: z.boolean().optional(),+ resourceType: z.enum(['document', 'task']),+});diff --git a/packages/types/src/work.ts b/packages/types/src/work.tsindex 1daab7d3ed2..63dc4752faf 100644--- a/packages/types/src/work.ts+++ b/packages/types/src/work.ts@@ -7,15 +7,23 @@ import type { TaskStatus } from './task';* generic Work lists.*/export type WorkType =- 'artboard' | 'canvas' | 'document' | 'external' | 'file' | 'goal_report' | 'task';+ 'artboard' | 'canvas' | 'document' | 'external' | 'file' | 'collection' | 'goal_report' | 'task';/** Work types the generic Work lists return; a `goal_report` is read through its goal. */export type ListedWorkType = Exclude<WorkType, 'goal_report'>;export type LinearWorkResourceType = 'linear_document' | 'linear_issue';export type GithubWorkResourceType = 'github_issue' | 'github_pull_request';+/**+ * A plain http(s) link an agent registered itself (`lh work create --url`), such+ * as a deployed site or a design file. Its resource identity is the normalized+ * URL. GitHub and Linear links are registered automatically under their own+ * resource types and are never stored as `link`.+ */+export type LinkWorkResourceType = 'link';/** Every resource type backed by the unified `external` Work type. */-export type ExternalWorkResourceType = GithubWorkResourceType | LinearWorkResourceType;+export type ExternalWorkResourceType =+ GithubWorkResourceType | LinearWorkResourceType | LinkWorkResourceType;export type WorkResourceType =- 'artboard' | 'canvas' | 'document' | ExternalWorkResourceType | 'file' | 'goal_report' | 'task';+ 'artboard' | 'canvas' | 'document' | ExternalWorkResourceType | 'file' | 'collection' | 'goal_report' | 'task';export type WorkVisibility = 'private' | 'public';/*** How a version changed the Work. Not derivable from `version === 1`: updating@@ -59,6 +67,14 @@ export interface ArtboardWorkPublishMetadata {}export interface WorkMetadata {+ /**+ * The agent may change this Work later through `lh work update`. Stamped once+ * when the Work identity is first registered and never changed afterwards:+ * Works collected automatically (completion scans, skill results, manifest+ * `work` configs without `agentEditable`) leave it unset and stay read-only+ * to the agent.+ */+ agentEditable?: boolean;agentShare?: AgentShareWorkProvenance;artboardPublish?: ArtboardWorkPublishMetadata;canvasPublish?: CanvasWorkPublishMetadata;@@ -121,11 +137,32 @@ export interface CanvasStorageItem {workId: string | null;}+/** One image of a `collection` Work, in display order. */+export interface CollectionWorkItem {+ caption?: string;+ /** The image's file-store id; the server checks the run owns it. */+ fileId: string;+ mimeType?: string;+ /** Durable URL of the image (`/f/<fileId>`), resolved by the server. */+ url: string;+}++/**+ * `collection` Work — the complete image list of this version. Every version+ * carries the full list: an update replaces it, never patches it.+ */+export interface CollectionWorkVersionMetadata {+ /** File id of the cover image; the first image when unset. */+ coverFileId?: string;+ items: CollectionWorkItem[];+}+export interface WorkVersionMetadata {agentDocumentId?: string;/** `external` GitHub PR Work — the branch the pull request merges into. */baseBranch?: string;canvas?: CanvasWorkVersionMetadata;+ collection?: CollectionWorkVersionMetadata;/*** `file` Work — the edited file's identity in the file store, when the entity* file was persisted. `filePath` is always present for a file Work; the@@ -325,12 +362,24 @@ export interface ArtboardWorkListItem extends WorkListBaseItem {type: 'artboard';}+/**+ * A set of images an agent collected into one Work (the `lobe-work` tool). Its+ * resource id is a generated `col_` id, so every create is a new collection. The+ * `works.url` column holds the cover image URL for list rows; the image list+ * lives in {@link CollectionWorkVersionMetadata}.+ */+export interface CollectionWorkListItem extends WorkListBaseItem {+ resourceType: 'collection';+ type: 'collection';+}+export type WorkListItem =| ArtboardWorkListItem| CanvasWorkListItem| DocumentWorkListItem| ExternalWorkListItem| FileWorkListItem+ | CollectionWorkListItem| TaskWorkListItem;export interface TaskWorkVersionEventItem extends TaskWorkListItem {@@ -357,12 +406,17 @@ export interface ArtboardWorkVersionEventItem extends ArtboardWorkListItem {version: WorkVersionPreview;}+export interface CollectionWorkVersionEventItem extends CollectionWorkListItem {+ version: WorkVersionPreview;+}+export type WorkVersionEventItem =| ArtboardWorkVersionEventItem| CanvasWorkVersionEventItem| DocumentWorkVersionEventItem| ExternalWorkVersionEventItem| FileWorkVersionEventItem+ | CollectionWorkVersionEventItem| TaskWorkVersionEventItem;export type WorkVersionEventMap = Record<string, WorkVersionEventItem[]>;@@ -405,17 +459,31 @@ export interface ArtboardWorkSummaryItem extends ArtboardWorkListItem {version: Pick<WorkVersionItem, 'createdAt' | 'id' | 'version'> | null;}+export interface CollectionWorkSummaryItem extends CollectionWorkListItem {+ event: WorkSummaryVersionPreview;+ totalCost: number | null;+ version: Pick<WorkVersionItem, 'createdAt' | 'id' | 'version'> | null;+}+export type WorkSummaryItem =| ArtboardWorkSummaryItem| CanvasWorkSummaryItem| DocumentWorkSummaryItem| ExternalWorkSummaryItem| FileWorkSummaryItem+ | CollectionWorkSummaryItem| TaskWorkSummaryItem;export type WorkSummaryMap = Record<string, WorkSummaryItem[]>;export interface RegisterDocumentWorkParams {agentDocumentId?: string | null;+ /**+ * Stamp the Work as agent-editable when this registration creates it. Ignored+ * when the Work already exists: editability is fixed at creation. See+ * {@link WorkMetadata.agentEditable}.+ */+ agentEditable?: boolean | null;+/** Agent that produced this version; also validates the agent-document binding when present. */agentId?: string | null;changeType: WorkVersionChangeType;@@ -446,9 +514,17 @@ export interface RegisterDocumentWorkParams {* `updated`).*/export interface RegisterFileWorkParams {+ /**+ * Stamp the Work as agent-editable when this registration creates it. Ignored+ * when the Work already exists: editability is fixed at creation. See+ * {@link WorkMetadata.agentEditable}.+ */+ agentEditable?: boolean | null;agentId?: string | null;cumulativeCost?: number | null;cumulativeUsage?: WorkVersionCumulativeUsage | null;+ /** Card description; defaults to `filePath`. */+ description?: string | null;/** The edited file's path within the operation — half of the resource identity. */filePath: string;messageId?: string | null;@@ -531,6 +607,12 @@ export interface DeleteWorkParams {}export interface RegisterExternalWorkParams {+ /**+ * Stamp the Work as agent-editable when this registration creates it. Ignored+ * when the Work already exists: editability is fixed at creation. See+ * {@link WorkMetadata.agentEditable}.+ */+ agentEditable?: boolean | null;agentId?: string | null;changeType: WorkVersionChangeType;/** Full body captured in the next version when named in `patchFields`. */@@ -628,6 +710,12 @@ export interface RegisterSkillToolResultWorkParams {export type SkillToolResultWorkInput = Omit<RegisterSkillToolResultWorkParams, 'provider'>;export interface RegisterTaskWorkParams {+ /**+ * Stamp the Work as agent-editable when this registration creates it. Ignored+ * when the Work already exists: editability is fixed at creation. See+ * {@link WorkMetadata.agentEditable}.+ */+ agentEditable?: boolean | null;agentId?: string | null;changeType: WorkVersionChangeType;cumulativeCost?: number | null;@@ -667,6 +755,8 @@ export interface WorkTaskTarget {export type WorkRegistrationIntent =| {action: 'create' | 'update' | 'delete';+ /** From the API's `work.agentEditable`; see {@link WorkMetadata.agentEditable}. */+ agentEditable?: boolean;changeType?: WorkVersionChangeType;targets: WorkTaskTarget[];type: 'task';@@ -682,6 +772,8 @@ export type WorkRegistrationIntent =action: 'register';document: {agentDocumentId?: string | null;+ /** From the API's `work.agentEditable`; see {@link WorkMetadata.agentEditable}. */+ agentEditable?: boolean;agentId?: string | null;description?: string | null;documentId: string;@@ -824,3 +916,75 @@ export interface TopicPullRequestItem extends TopicPullRequestWork {*/vouched: boolean;}++/** Tool identity stamped on Work versions written by `lh work create|update`. */+export const AGENT_WORK_CLI_TOOL_IDENTIFIER = 'lobehub-cli';++/**+ * What an agent registers itself as a Work: a file it produced (already+ * uploaded to the file store), a plain http(s) link, or a collection of images it+ * collected.+ */+export type CreateAgentWorkInput =+ | {+ description?: string;+ file: {+ fileId: string;+ /** Absolute path of the produced file; with the topic it forms the Work identity. */+ filePath: string;+ fileSize?: number;+ fileUrl?: string;+ mimeType?: string;+ };+ title?: string;+ type: 'file';+ }+ | {+ description?: string;+ title: string;+ type: 'link';+ url: string;+ }+ | ({+ description?: string;+ title: string;+ type: 'collection';+ } & CollectionWorkVersionMetadata);++/**+ * A new version of an agent-created Work. Fields left out keep the current+ * version's values. `file` applies to file Works and `collection` to collection+ * Works, where it replaces the whole image list. A link Work's URL is its+ * identity and does not change; a new link is a new Work.+ */+export interface UpdateAgentWorkInput {+ collection?: CollectionWorkVersionMetadata;+ description?: string;+ file?: Omit<Extract<CreateAgentWorkInput, { type: 'file' }>['file'], 'filePath'>;+ title?: string;+ workId: string;+}++/** The run an agent Work is registered from, resolved server-side from its operation. */+export interface AgentWorkRunContext {+ agentId?: string | null;+ /** The assistant message of the tool call, when a builtin tool (not the CLI) writes. */+ messageId?: string | null;+ operationId: string;+ /**+ * Top of the operation tree `operationId` runs in, stamped on versions as+ * `rootOperationId` so run completion can fill their cost. Defaults to+ * `operationId`.+ */+ rootOperationId?: string;+ threadId?: string | null;+ /** Tool call id of a builtin-tool write; a retried call does not add a second version. */+ toolCallId?: string | null;+ /** Defaults to {@link AGENT_WORK_CLI_TOOL_IDENTIFIER}. */+ toolIdentifier?: string;+ topicId: string;+ userId: string;+}++/** Most images one collection Work holds. */+export const COLLECTION_WORK_MAX_ITEMS = 50;diff --git a/src/features/CollectionModal/CollectionGrid.tsx b/src/features/CollectionModal/CollectionGrid.tsxnew file mode 100644index 00000000000..e008bed4a1e--- /dev/null+++ b/src/features/CollectionModal/CollectionGrid.tsx@@ -0,0 +1,63 @@+import type { CollectionWorkItem } from '@lobechat/types';+import { Image, PreviewGroup, Text } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';++import { downloadPreviewImage } from '@/features/Conversation/Messages/components/downloadPreviewImage';++const styles = stylex.create({+ caption: {+ color: cssVar.colorTextSecondary,+ fontSize: 12,+ lineHeight: 1.5,+ },+ grid: {+ display: 'grid',+ // Keep in step with COLLECTION_GRID_GAP / COLLECTION_TILE_SIZE in ./layout; StyleX needs literals.+ gap: 12,+ // auto-fit collapses unused tracks, so fewer images than columns stretch to fill the row.+ gridTemplateColumns: 'repeat(auto-fit, minmax(min(200px, 100%), 1fr))',+ },+ tile: {+ display: 'flex',+ flexDirection: 'column',+ gap: 6,+ minWidth: 0,+ },+});++interface CollectionGridProps {+ items: CollectionWorkItem[];+}++/**+ * Square tiles of every collection image. One preview group lets the viewer step+ * through the collection; its download action saves `/f/<id>` images under their+ * stored names.+ */+const CollectionGrid = ({ items }: CollectionGridProps) => (+ <PreviewGroup preview={{ onDownload: downloadPreviewImage }}>+ <div {...stylex.props(styles.grid)}>+ {items.map((item) => (+ <div key={item.fileId} {...stylex.props(styles.tile)}>+ <Image+ alt={item.caption ?? ''}+ objectFit={'cover'}+ src={item.url}+ // The ratio goes on the <img>: on the root it squares the frame while the+ // image keeps its own height, leaving an empty strip under landscape shots.+ styles={{ image: { aspectRatio: 1 } }}+ width={'100%'}+ />+ {item.caption && (+ <Text ellipsis={{ tooltip: true }} {...stylex.props(styles.caption)}>+ {item.caption}+ </Text>+ )}+ </div>+ ))}+ </div>+ </PreviewGroup>+);++export default CollectionGrid;diff --git a/src/features/CollectionModal/index.tsx b/src/features/CollectionModal/index.tsxnew file mode 100644index 00000000000..1f18859656b--- /dev/null+++ b/src/features/CollectionModal/index.tsx@@ -0,0 +1,54 @@+'use client';++import type { CollectionWorkItem } from '@lobechat/types';+import { createModal, Empty } from '@lobehub/ui';+import { t } from 'i18next';+import { useTranslation } from 'react-i18next';++import AsyncBoundary from '@/components/AsyncBoundary';++import CollectionGrid from './CollectionGrid';+import { getCollectionModalWidth } from './layout';+import { useCollectionItems } from './useCollectionItems';++export interface CollectionModalParams {+ /**+ * The collection's images when the caller already has them (summary rows, the+ * share profile). Without them the modal loads the latest version, which only+ * the Work's owner may read.+ */+ items?: CollectionWorkItem[];+ title?: string | null;+ workId?: string;+}++const CollectionModalContent = ({+ items,+ workId,+}: Pick<CollectionModalParams, 'items' | 'workId'>) => {+ const { t } = useTranslation('chat');+ const { error, images, isLoading, retry } = useCollectionItems({ items, workId });++ return (+ <AsyncBoundary+ data={images}+ empty={<Empty description={t('workingPanel.works.collectionEmpty')} />}+ error={error}+ isEmpty={!error && !images?.length}+ isLoading={isLoading}+ onRetry={retry}+ >+ {images && <CollectionGrid items={images} />}+ </AsyncBoundary>+ );+};++export const createCollectionModal = ({ items, title, workId }: CollectionModalParams) =>+ createModal({+ content: <CollectionModalContent items={items} workId={workId} />,+ footer: null,+ maskClosable: true,+ styles: { content: { maxHeight: '75vh', overflowY: 'auto' } },+ title: title?.trim() || t('workingPanel.works.collectionUntitled', { ns: 'chat' }),+ width: getCollectionModalWidth(items?.length),+ });diff --git a/src/features/CollectionModal/layout.test.ts b/src/features/CollectionModal/layout.test.tsnew file mode 100644index 00000000000..4bc5ce6bf56--- /dev/null+++ b/src/features/CollectionModal/layout.test.ts@@ -0,0 +1,15 @@+import { describe, expect, it } from 'vitest';++import { getCollectionModalWidth } from './layout';++describe('getCollectionModalWidth', () => {+ it('fits the modal to a small collection', () => {+ expect(getCollectionModalWidth(1)).toBe('min(95vw, 460px)');+ expect(getCollectionModalWidth(2)).toBe('min(95vw, 460px)');+ });++ it('caps at four columns, the width used when the count is unknown', () => {+ expect(getCollectionModalWidth(12)).toBe('min(95vw, 884px)');+ expect(getCollectionModalWidth()).toBe('min(95vw, 884px)');+ });+});diff --git a/src/features/CollectionModal/layout.ts b/src/features/CollectionModal/layout.tsnew file mode 100644index 00000000000..d4b33e8f5fd--- /dev/null+++ b/src/features/CollectionModal/layout.ts@@ -0,0 +1,21 @@+/** Width of one square tile in the collection grid. */+const COLLECTION_TILE_SIZE = 200;+const COLLECTION_GRID_GAP = 12;++/** Two columns at least, so a single image and the title get room; the grid stretches it. */+const MIN_COLUMNS = 2;+const MAX_COLUMNS = 4;+/** The modal body's horizontal padding (both sides). */+const MODAL_PADDING_X = 48;++/**+ * Modal width that fits the images instead of a fixed wide panel: two images+ * would otherwise sit in the left third of a 960px modal. Without a known count+ * (the modal loads the images itself) it falls back to four columns.+ */+export const getCollectionModalWidth = (count?: number) => {+ const columns = Math.min(Math.max(count ?? MAX_COLUMNS, MIN_COLUMNS), MAX_COLUMNS);+ const content = columns * COLLECTION_TILE_SIZE + (columns - 1) * COLLECTION_GRID_GAP;++ return `min(95vw, ${content + MODAL_PADDING_X}px)`;+};diff --git a/src/features/CollectionModal/loader.ts b/src/features/CollectionModal/loader.tsnew file mode 100644index 00000000000..c1ea7ca7194--- /dev/null+++ b/src/features/CollectionModal/loader.ts@@ -0,0 +1,7 @@+import type { CollectionModalParams } from '.';++/** Load the collection viewer on first open, so cards do not bundle the image viewer. */+export const openCollectionModal = async (params: CollectionModalParams) => {+ const { createCollectionModal } = await import('.');+ return createCollectionModal(params);+};diff --git a/src/features/CollectionModal/useCollectionItems.test.ts b/src/features/CollectionModal/useCollectionItems.test.tsnew file mode 100644index 00000000000..8ca0bc726af--- /dev/null+++ b/src/features/CollectionModal/useCollectionItems.test.ts@@ -0,0 +1,76 @@+import { act, renderHook } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { useCollectionItems } from './useCollectionItems';++const mocks = vi.hoisted(() => ({+ revalidate: vi.fn(),+ useFetchWorkVersions: vi.fn(),+}));++const store = vi.hoisted(() => ({ current: undefined as any }));++vi.mock('@/store/work', async () => {+ const { create: createStore } = await import('zustand');+ store.current = createStore<{ workVersionsMap: Record<string, unknown[]> }>(() => ({+ workVersionsMap: {},+ }));+ return {+ useWorkStore: store.current,+ workActions: { useFetchWorkVersions: mocks.useFetchWorkVersions },+ workSelectors: {+ workVersions: (workId: string) => (s: any) => s.workVersionsMap[workId],+ },+ };+});++const image = (n: number) => ({ fileId: `file-${n}`, url: `https://app.example.com/f/file-${n}` });+const version = (...images: ReturnType<typeof image>[]) => ({+ metadata: { collection: { items: images } },+});++describe('useCollectionItems', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ store.current.setState({ workVersionsMap: {} });+ mocks.useFetchWorkVersions.mockReturnValue({ error: undefined, revalidate: mocks.revalidate });+ });++ it('shows the images it is given without loading the versions', () => {+ const { result } = renderHook(() =>+ useCollectionItems({ items: [image(1), image(2)], workId: 'work-1' }),+ );++ expect(result.current).toMatchObject({ images: [image(1), image(2)], isLoading: false });+ expect(mocks.useFetchWorkVersions).toHaveBeenCalledWith(null, expect.anything());+ });++ it('shows the latest version and follows a refresh of the Work versions', () => {+ // Versions come newest first.+ store.current.setState({+ workVersionsMap: { 'work-c': [version(image(3)), version(image(1))] },+ });++ const { result } = renderHook(() => useCollectionItems({ workId: 'work-c' }));++ expect(mocks.useFetchWorkVersions).toHaveBeenCalledWith(+ { workId: 'work-c' },+ expect.anything(),+ );+ expect(result.current.images).toEqual([image(3)]);++ // The agent replaced the images; the run-end refresh lands a new version.+ act(() => {+ store.current.setState({+ workVersionsMap: { 'work-c': [version(image(4), image(5)), version(image(3))] },+ });+ });+ expect(result.current.images).toEqual([image(4), image(5)]);+ });++ it('is loading until the versions arrive', () => {+ const { result } = renderHook(() => useCollectionItems({ workId: 'work-pending' }));++ expect(result.current).toMatchObject({ images: undefined, isLoading: true });+ });+});diff --git a/src/features/CollectionModal/useCollectionItems.ts b/src/features/CollectionModal/useCollectionItems.tsnew file mode 100644index 00000000000..ff38c33e84a--- /dev/null+++ b/src/features/CollectionModal/useCollectionItems.ts@@ -0,0 +1,39 @@+import type { CollectionWorkItem } from '@lobechat/types';+import { useMemo } from 'react';++import { useWorkStore, workActions, workSelectors } from '@/store/work';++/**+ * The images a collection viewer shows: the ones the caller passed, else those of+ * the Work's latest version (readable by its owner only).+ *+ * The versions come from the Work version replica (`work:versions`), the one the+ * sidebar timeline reads, so the run-end and Work-change refreshes that+ * revalidate it also update an open viewer after the agent replaces the images.+ */+export const useCollectionItems = ({+ items,+ workId,+}: {+ items?: CollectionWorkItem[];+ workId?: string;+}) => {+ const params = useMemo(() => (items || !workId ? null : { workId }), [items, workId]);+ const { error, revalidate } = workActions.useFetchWorkVersions(params, {+ revalidateOnFocus: false,+ });+ // Versions come newest first.+ const versions = useWorkStore((s) =>+ params ? workSelectors.workVersions(params.workId)(s) : undefined,+ );+ const latest = versions ? (versions[0]?.metadata?.collection?.items ?? []) : undefined;++ return {+ error: items || latest ? undefined : error,+ images: items ?? latest,+ isLoading: Boolean(params) && latest === undefined && !error,+ retry: () => {+ void revalidate();+ },+ };+};diff --git a/src/features/Conversation/Messages/MessageWorks/useVisitorWorkOpen.test.ts b/src/features/Conversation/Messages/MessageWorks/useVisitorWorkOpen.test.tsindex 3e4eaa84296..c00d86833b8 100644--- a/src/features/Conversation/Messages/MessageWorks/useVisitorWorkOpen.test.ts+++ b/src/features/Conversation/Messages/MessageWorks/useVisitorWorkOpen.test.ts@@ -5,6 +5,9 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';import { useVisitorWorkOpen } from './useVisitorWorkOpen';const openFilePreview = vi.fn();+const { openCollectionModal } = vi.hoisted(() => ({ openCollectionModal: vi.fn() }));++vi.mock('@/features/CollectionModal/loader', () => ({ openCollectionModal }));const conversationState = { context: { agentShareId: 'share_1', topicId: 'tpc_1' } };vi.mock('../../store', () => ({@@ -32,6 +35,25 @@ const fileWork = (fileUrl?: string) =>describe('useVisitorWorkOpen', () => {beforeEach(() => {openFilePreview.mockReset();+ openCollectionModal.mockReset();+ });++ it('opens a collection with the images its card carries, and never asks for the versions', () => {+ const items = [{ fileId: 'file_1', url: 'https://app.lobehub.com/f/file_1' }];+ const { result } = renderHook(() => useVisitorWorkOpen());++ result.current({+ event: { metadata: { collection: { items } } },+ id: 'wk_collection',+ title: 'Shelf',+ type: 'collection',+ } as unknown as WorkSummaryItem);+ expect(openCollectionModal).toHaveBeenCalledWith({ items, title: 'Shelf' });++ // A row without images has nothing a visitor may load.+ openCollectionModal.mockReset();+ result.current({ id: 'wk_collection', type: 'collection' } as unknown as WorkSummaryItem);+ expect(openCollectionModal).not.toHaveBeenCalled();});it('previews a file Work in the portal from its public URL instead of a new tab', () => {diff --git a/src/features/Conversation/Messages/MessageWorks/useVisitorWorkOpen.ts b/src/features/Conversation/Messages/MessageWorks/useVisitorWorkOpen.tsindex 55548b4d1c8..5c09ced3863 100644--- a/src/features/Conversation/Messages/MessageWorks/useVisitorWorkOpen.ts+++ b/src/features/Conversation/Messages/MessageWorks/useVisitorWorkOpen.ts@@ -1,6 +1,7 @@import type { WorkSummaryItem } from '@lobechat/types';import { useCallback } from 'react';+import { openCollectionModal } from '@/features/CollectionModal/loader';import { getWorkTypeDescriptor, isSafeExternalUrl } from '@/features/Work/descriptors';import { createShareVisitorDocumentModal } from '@/features/Work/ShareVisitorDocumentModal';import { useAppOrigin } from '@/hooks/useAppOrigin';@@ -55,6 +56,11 @@ export const useVisitorWorkOpen = () => {window.open(target.url, '_blank', 'noopener,noreferrer');return;}+ case 'collection': {+ // A visitor cannot read the Work's versions, so only a row carrying its images opens.+ if (target.items) void openCollectionModal({ items: target.items, title: target.title });+ return;+ }default: {return;}diff --git a/src/features/Conversation/WorkingSidebar/WorksSection/WorkVersionHistoryCard.tsx b/src/features/Conversation/WorkingSidebar/WorksSection/WorkVersionHistoryCard.tsxindex 7faaf2498bd..3097d7648d4 100644--- a/src/features/Conversation/WorkingSidebar/WorksSection/WorkVersionHistoryCard.tsx+++ b/src/features/Conversation/WorkingSidebar/WorksSection/WorkVersionHistoryCard.tsx@@ -8,6 +8,7 @@ import { memo, useState } from 'react';import TaskPriorityTag from '@/features/AgentTasks/features/TaskPriorityTag';import TaskStatusTag from '@/features/AgentTasks/features/TaskStatusTag';import { openArtboard } from '@/features/Artboard/openArtboard';+import { openCollectionModal } from '@/features/CollectionModal/loader';import { getWorkTypeDescriptor, isSafeExternalUrl } from '@/features/Work/descriptors';import { useResourceDeletedPrompt } from '@/features/Work/useResourceDeletedPrompt';import { useChatStore } from '@/store/chat';@@ -116,6 +117,9 @@ const WorkVersionHistoryCard = memo<{ work: WorkListItem }>(({ work }) => {case 'filePreview': {return () => openFilePreview({ fileId: openTarget.fileId });}+ case 'collection': {+ return () => void openCollectionModal(openTarget);+ }case 'task': {return resourceDeleted? () => promptResourceDeleted(work)diff --git a/src/features/Work/CollectionFan.tsx b/src/features/Work/CollectionFan.tsxnew file mode 100644index 00000000000..c667ddfadb1--- /dev/null+++ b/src/features/Work/CollectionFan.tsx@@ -0,0 +1,67 @@+'use client';++import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';+import { memo } from 'react';++const styles = stylex.create({+ fan: {+ flexShrink: 0,+ height: 36,+ position: 'relative',+ width: 36,+ },+ image: {+ borderColor: cssVar.colorBgElevated,+ borderRadius: 5,+ borderStyle: 'solid',+ borderWidth: 1.5,+ boxShadow: '0 1px 3px rgb(0 0 0 / 18%)',+ height: 28,+ insetBlockStart: 4,+ insetInlineStart: 5,+ objectFit: 'cover',+ position: 'absolute',+ width: 26,+ },+ transform: (transform: string) => ({ transform }),+});++/**+ * Back cards first, cover last so it paints on top. Two images tilt the back+ * one to the right; three spread the back pair to both sides.+ */+const TRANSFORMS: Record<number, string[]> = {+ 2: ['translateX(4px) rotate(10deg)', 'translateX(-2px) rotate(-4deg)'],+ 3: ['translateX(-5px) rotate(-12deg)', 'translateX(5px) rotate(12deg)', 'rotate(0deg)'],+};++interface CollectionFanProps {+ /** Two or three image URLs, cover first. */+ urls: string[];+}++/** Collection card thumbnail: the cover in front with up to two more images fanned behind it. */+const CollectionFan = memo<CollectionFanProps>(({ urls }) => {+ const [cover, ...rest] = urls;+ const ordered = [...rest, cover];+ const transforms = TRANSFORMS[ordered.length] ?? TRANSFORMS[3];++ return (+ <div {...stylex.props(styles.fan)}>+ {ordered.map((url, index) => (+ <img+ alt=""+ key={url}+ loading="lazy"+ src={url}+ {...stylex.props(styles.image, styles.transform(transforms[index]))}+ />+ ))}+ </div>+ );+});++CollectionFan.displayName = 'CollectionFan';++export default CollectionFan;diff --git a/src/features/Work/WorkSummaryCard.tsx b/src/features/Work/WorkSummaryCard.tsxindex 926a11b38b4..f1c2fd7ab7b 100644--- a/src/features/Work/WorkSummaryCard.tsx+++ b/src/features/Work/WorkSummaryCard.tsx@@ -8,6 +8,7 @@ import { memo } from 'react';import { useTranslation } from 'react-i18next';import { openArtboard } from '@/features/Artboard/openArtboard';+import { openCollectionModal } from '@/features/CollectionModal/loader';import { useChatStore } from '@/store/chat';import { useDensityTokens } from '@/styles/density';import { sidebarRow } from '@/styles/density.stylex';@@ -16,7 +17,15 @@ import { getWorkVersionTotalTokens } from '@/utils/workCumulativeUsage';import { formatWorkVersionCost } from '@/utils/workVersionCost';import CanvasWorkCard from './CanvasWorkCard';-import { getWorkTypeDescriptor, type WorkBranch, type WorkIcon } from './descriptors';+import CollectionFan from './CollectionFan';+import {+ getCollectionCoverUrl,+ getCollectionFanUrls,+ getCollectionImageCount,+ getWorkTypeDescriptor,+ type WorkBranch,+ type WorkIcon,+} from './descriptors';import { openExternalWork } from './openExternalWork';import { useResourceDeletedPrompt } from './useResourceDeletedPrompt';@@ -75,7 +84,20 @@ const styles = createStaticStyles(({ css, cssVar }) => ({identifierIcon: css`flex-shrink: 0;`,+ cover: css`+ flex-shrink: 0;+ display: block;+ border-radius: 4px;+ object-fit: cover;+ `,+ coverFill: css`+ display: block;+ width: 100%;+ height: 100%;+ object-fit: cover;+ `,icon: css`+ overflow: hidden;flex-shrink: 0;width: 36px;@@ -326,7 +348,23 @@ const WorkSummaryCard = memo<WorkSummaryCardProps>(// (e.g. `QA-1989`, `owner/repo#2`) on the card itself, unless the title// already fell back to it.const identifier = descriptor.getIdentifier(item);- const metaIdentifier = identifier && identifier !== title ? identifier : null;+ // A collection shows its cover in place of the icon and its image count in the identifier slot.+ const coverUrl = item.type === 'collection' ? getCollectionCoverUrl(item) : null;+ const imageCount = item.type === 'collection' ? getCollectionImageCount(item) : null;+ // The card fans a multi-image collection so it reads as a set; smaller rows keep the cover alone.+ const fanUrls = item.type === 'collection' ? getCollectionFanUrls(item) : [];+ const metaIdentifier =+ imageCount !== null+ ? t('workingPanel.works.collectionCount', { count: imageCount })+ : identifier && identifier !== title+ ? identifier+ : null;+ const renderIcon = (size: number) =>+ coverUrl ? (+ <img alt="" className={styles.cover} height={size} src={coverUrl} width={size} />+ ) : (+ <Icon size={size} />+ );const identifierIcon = descriptor.getIdentifierIcon?.(item) ?? null;const branch = descriptor.getBranch?.(item) ?? null;const description = descriptor.getDescription(item);@@ -370,6 +408,10 @@ const WorkSummaryCard = memo<WorkSummaryCardProps>(openFilePreview({ fileId: openTarget.fileId });return;}+ case 'collection': {+ void openCollectionModal(openTarget);+ return;+ }case 'task': {openTaskDetail(openTarget.taskId);}@@ -396,7 +438,7 @@ const WorkSummaryCard = memo<WorkSummaryCardProps>(onClick={clickable ? handleOpen : undefined}><Center className={styles.rowIcon} title={stateLabel}>- <Icon size={density.iconSize} />+ {renderIcon(density.iconSize)}</Center><Flexbox flex={1} style={{ minWidth: 0 }}><Text ellipsis className={styles.rowTitle} title={title}>@@ -432,7 +474,7 @@ const WorkSummaryCard = memo<WorkSummaryCardProps>(onClick={clickable ? handleOpen : undefined}><Center className={styles.inlineIcon} title={stateLabel}>- <Icon size={17} />+ {renderIcon(17)}</Center><Flexbox flex={1} gap={2} style={{ minWidth: 0 }}><Flexbox horizontal align={'center'} gap={8} style={{ minWidth: 0 }}>@@ -466,9 +508,17 @@ const WorkSummaryCard = memo<WorkSummaryCardProps>(gap={12}onClick={clickable ? handleOpen : undefined}>- <Flexbox align={'center'} className={styles.icon} justify={'center'} title={stateLabel}>- <Icon size={18} />- </Flexbox>+ {fanUrls.length > 1 ? (+ <CollectionFan urls={fanUrls} />+ ) : (+ <Flexbox align={'center'} className={styles.icon} justify={'center'} title={stateLabel}>+ {coverUrl ? (+ <img alt="" className={styles.coverFill} src={coverUrl} />+ ) : (+ <Icon size={18} />+ )}+ </Flexbox>+ )}<Flexbox flex={1} gap={2} style={{ minWidth: 0 }}><Flexbox horizontal align={'center'} gap={8} style={{ minWidth: 0 }}><Text ellipsis className={styles.title} style={{ flex: 1 }} title={title}>diff --git a/src/features/Work/descriptors.test.ts b/src/features/Work/descriptors.test.tsindex 76314f357e9..63f3bbed834 100644--- a/src/features/Work/descriptors.test.ts+++ b/src/features/Work/descriptors.test.ts@@ -1,6 +1,11 @@import { describe, expect, it } from 'vitest';-import { getWorkTypeDescriptor } from './descriptors';+import {+ getCollectionCoverUrl,+ getCollectionFanUrls,+ getCollectionImageCount,+ getWorkTypeDescriptor,+} from './descriptors';describe('getWorkTypeDescriptor', () => {it('returns a usable fallback descriptor for an unknown work type', () => {@@ -74,6 +79,30 @@ describe('getWorkTypeDescriptor', () => {});});+ it('shows the description an agent gave the file over its path', () => {+ const item = {+ ...baseFileItem,+ description: 'Quarterly numbers for the board',+ event: { metadata: { filePath: '/tmp/deck/slides.pptx' } },+ } as any;++ expect(getWorkTypeDescriptor(item).getDescription(item)).toBe(+ 'Quarterly numbers for the board',+ );+ });++ it('shows the title an agent gave the file over the file name', () => {+ const item = { ...baseFileItem, title: 'Q3 report' } as any;++ expect(getWorkTypeDescriptor(item).getTitle(item)).toBe('Q3 report');+ });++ it('falls back to the file name when the row has no title', () => {+ const item = { ...baseFileItem, title: '' } as any;++ expect(getWorkTypeDescriptor(item).getTitle(item)).toBe('slides.pptx');+ });+it('yields no target when neither fileId nor a safe url exists', () => {const item = { ...baseFileItem, url: null } as any;@@ -99,6 +128,80 @@ describe('getWorkTypeDescriptor', () => {});});+ describe('collection', () => {+ const image = (n: number) => ({+ fileId: `file-${n}`,+ mimeType: 'image/png',+ url: `https://app.example.com/f/file-${n}`,+ });+ const listRow = {+ description: null,+ id: 'work-collection-1',+ identifier: null,+ resourceId: 'col_1',+ resourceType: 'collection',+ title: 'Top ten CD shelf',+ type: 'collection',+ url: 'https://app.example.com/f/file-2',+ };+ const summaryRow = {+ ...listRow,+ event: { metadata: { collection: { coverFileId: 'file-2', items: [image(1), image(2)] } } },+ };++ it('opens the viewer with the images a summary row carries', () => {+ const item = summaryRow as any;++ expect(getWorkTypeDescriptor(item).getOpenTarget(item)).toEqual({+ items: [image(1), image(2)],+ kind: 'collection',+ title: 'Top ten CD shelf',+ workId: 'work-collection-1',+ });+ expect(getCollectionImageCount(item)).toBe(2);+ expect(getCollectionCoverUrl(item)).toBe(image(2).url);+ });++ it('leaves loading the images to the viewer for a list row', () => {+ const item = listRow as any;++ expect(getWorkTypeDescriptor(item).getOpenTarget(item)).toEqual({+ items: undefined,+ kind: 'collection',+ title: 'Top ten CD shelf',+ workId: 'work-collection-1',+ });+ expect(getCollectionImageCount(item)).toBeNull();+ // List rows show the cover denormalized into works.url.+ expect(getCollectionCoverUrl(item)).toBe('https://app.example.com/f/file-2');+ });++ it('falls back to the first image without a named cover, and drops non-http(s) covers', () => {+ const firstImage = {+ ...summaryRow,+ event: { metadata: { collection: { items: [image(3), image(1)] } } },+ } as any;+ expect(getCollectionCoverUrl(firstImage)).toBe(image(3).url);++ const unsafe = { ...listRow, url: 'javascript:alert(1)' } as any;+ expect(getCollectionCoverUrl(unsafe)).toBeNull();+ });++ it('fans out up to three images with the cover in front', () => {+ const four = {+ ...summaryRow,+ event: {+ metadata: {+ collection: { coverFileId: 'file-3', items: [image(1), image(2), image(3), image(4)] },+ },+ },+ } as any;+ expect(getCollectionFanUrls(four)).toEqual([image(3).url, image(1).url, image(2).url]);+ // A list row knows only the cover, so there is nothing to fan.+ expect(getCollectionFanUrls(listRow as any)).toEqual(['https://app.example.com/f/file-2']);+ });+ });+describe('canvas open target', () => {const canvasItem = (eventVersion: number, currentVersion: number) =>({diff --git a/src/features/Work/descriptors.tsx b/src/features/Work/descriptors.tsxindex 38207a8a566..8b4dabadbd3 100644--- a/src/features/Work/descriptors.tsx+++ b/src/features/Work/descriptors.tsx@@ -1,5 +1,6 @@import { classifyEditedFile, getBasename } from '@lobechat/builtin-tools/fileEditScan';import {+ type CollectionWorkItem,type ExternalWorkResourceType,type ListedWorkType,type WorkListItem,@@ -22,6 +23,7 @@ import {FileTextIcon,FileTypeIcon,GitPullRequestDraftIcon,+ ImagesIcon,LinkIcon,PanelsTopLeftIcon,PresentationIcon,@@ -132,7 +134,13 @@ export type WorkOpenTarget =* chat portal (WorkGallery), so they don't recompute the file-metadata lookup.*/| { fileId: string; kind: 'filePreview'; url?: string }- | { canvasId: string; kind: 'canvas'; version?: number };+ | { canvasId: string; kind: 'canvas'; version?: number }+ /**+ * Grid viewer of a collection Work. Summary rows carry the version's images;+ * list rows only know the cover, so the viewer loads the images itself when+ * `items` is missing.+ */+ | { items?: CollectionWorkItem[]; kind: 'collection'; title?: string | null; workId: string };/*** Client-side allowlist for external Work URLs (defense in depth over the@@ -252,6 +260,41 @@ const getFileWorkMetadata = (item: WorkItemOfType<'file'>): WorkVersionMetadataconst getFileWorkPath = (item: WorkItemOfType<'file'>): string | null =>getFileWorkMetadata(item)?.filePath ?? item.description?.trim() ?? null;+/** The images of a collection summary row; list rows carry no version metadata. */+const getCollectionItems = (+ item: WorkItemOfType<'collection'>,+): CollectionWorkItem[] | undefined =>+ 'event' in item ? (item.event?.metadata?.collection?.items ?? undefined) : undefined;++/**+ * The cover a collection card shows: the version's named cover, else its first+ * image, else the denormalized `works.url` list rows carry. Only http(s) URLs.+ */+export const getCollectionCoverUrl = (item: WorkItemOfType<'collection'>): string | null => {+ const collection = 'event' in item ? item.event?.metadata?.collection : undefined;+ const cover = collection?.coverFileId+ ? collection.items.find((image) => image.fileId === collection.coverFileId)+ : undefined;+ const url = (cover ?? collection?.items[0])?.url ?? item.url;+ return isSafeExternalUrl(url) ? url : null;+};++/**+ * Up to three images a collection card fans out, cover first. Fewer than two means+ * there is nothing to fan: list rows know only the cover.+ */+export const getCollectionFanUrls = (item: WorkItemOfType<'collection'>): string[] => {+ const cover = getCollectionCoverUrl(item);+ const others = (getCollectionItems(item) ?? [])+ .map((image) => image.url)+ .filter((url) => url !== cover && isSafeExternalUrl(url));+ return [...(cover ? [cover] : []), ...others].slice(0, 3);+};++/** Image count of a collection summary row, `null` for list rows that do not know it. */+export const getCollectionImageCount = (item: WorkItemOfType<'collection'>): number | null =>+ getCollectionItems(item)?.length ?? null;+export const WORK_TYPE_DESCRIPTORS: {[T in ListedWorkType]: WorkTypeDescriptor<WorkItemOfType<T>>;} = {@@ -304,9 +347,9 @@ export const WORK_TYPE_DESCRIPTORS: {// aggregate card instead. The version metadata carries the file identity// (path / url); plain list rows fall back to the denormalized `works` columns.file: {- // Subtitle is the file path (metadata), falling back to the denormalized- // description column for list rows without version metadata.- getDescription: (item) => getFileWorkPath(item),+ // Subtitle is the description an agent gave the file; otherwise the+ // denormalized description column holds the file path.+ getDescription: (item) => item.description?.trim() || getFileWorkPath(item),// Pick the branded file-type badge from the file's extension; unclassifiable// paths (or a path-less list row) fall back to the generic file-text glyph.getIcon: (item) => {@@ -329,13 +372,13 @@ export const WORK_TYPE_DESCRIPTORS: {if (metadata?.fileId) return { fileId: metadata.fileId, kind: 'filePreview', url: safeUrl };return safeUrl ? { kind: 'external', url: safeUrl } : null;},- // Title is the file name (basename of the path), falling back to the- // denormalized title column.+ // The stored title wins: scanned Works store the basename there on every+ // version, and an agent-created Work (`lh work create --title`) stores the+ // title the agent chose. The path basename covers rows without a title.getTitle: (item) => {+ if (item.title?.trim()) return item.title;const path = getFileWorkPath(item);- // `getBasename` returns '' for a segment-less path; fall through to the- // denormalized title in that case (matching the previous null-coalescing).- return (path ? getBasename(path) : '') || item.title;+ return path ? getBasename(path) : item.title;},},external: {@@ -373,6 +416,18 @@ export const WORK_TYPE_DESCRIPTORS: {getStateLabelKey: (item) => getGithubState(item)?.labelKey ?? null,getTitle: (item) => item.title,},+ collection: {+ getDescription: (item) => item.description?.trim() ?? null,+ getIcon: () => ImagesIcon,+ getIdentifier: () => null,+ getOpenTarget: (item) => ({+ items: getCollectionItems(item),+ kind: 'collection',+ title: item.title,+ workId: item.id,+ }),+ getTitle: (item) => item.title,+ },task: {getDescription: (item) => item.task.instruction?.trim() ?? null,getIcon: () => ClipboardListIcon,diff --git a/src/features/WorkGallery/WorkPreview.tsx b/src/features/WorkGallery/WorkPreview.tsxindex f076580631d..de4bad41f08 100644--- a/src/features/WorkGallery/WorkPreview.tsx+++ b/src/features/WorkGallery/WorkPreview.tsx@@ -7,7 +7,7 @@ import { CheckCircle2Icon, GitPullRequestIcon } from 'lucide-react';import { memo } from 'react';import { useTranslation } from 'react-i18next';-import { getWorkTypeDescriptor } from '@/features/Work/descriptors';+import { getCollectionCoverUrl, getWorkTypeDescriptor } from '@/features/Work/descriptors';import LinearIcon from '@/features/Work/icons/LinearIcon';const styles = createStaticStyles(({ css }) => ({@@ -64,6 +64,17 @@ const styles = createStaticStyles(({ css }) => ({background: color-mix(in srgb, ${cssVar.colorBgElevated} 88%, transparent);backdrop-filter: blur(12px);`,+ collectionImage: css`+ position: absolute;+ inset: 0;++ display: block;++ width: 100%;+ height: 100%;++ object-fit: cover;+ `,grid: css`position: absolute;inset: 0;@@ -186,6 +197,17 @@ const WorkPreview = memo<WorkPreviewProps>(({ item, title }) => {const isLinear = item.resourceType.startsWith('linear_');const taskStatus = item.resourceType === 'task' ? item.task.status : null;const status = item.status || taskStatus;+ const collectionCover = item.type === 'collection' ? getCollectionCoverUrl(item) : null;++ if (collectionCover)+ return (+ <div className={styles.cover}>+ <img alt={title} className={styles.collectionImage} src={collectionCover} />+ <div className={styles.coverBadge}>+ <DescriptorIcon size={17} />+ </div>+ </div>+ );return (<div className={styles.cover}>diff --git a/src/features/WorkGallery/WorkPreviewCard.tsx b/src/features/WorkGallery/WorkPreviewCard.tsxindex 726c61a6c6d..149517a764c 100644--- a/src/features/WorkGallery/WorkPreviewCard.tsx+++ b/src/features/WorkGallery/WorkPreviewCard.tsx@@ -157,6 +157,9 @@ const workTypeKey = (item: WorkSummaryItem) => {case 'file': {return 'work.type.file';}+ case 'collection': {+ return 'work.type.collection';+ }case 'github_issue': {return 'work.type.githubIssue';}@@ -169,6 +172,9 @@ const workTypeKey = (item: WorkSummaryItem) => {case 'linear_issue': {return 'work.type.linearIssue';}+ case 'link': {+ return 'work.type.link';+ }case 'task': {return 'work.type.task';}diff --git a/src/features/WorkGallery/useOpenWork.ts b/src/features/WorkGallery/useOpenWork.tsindex e8181e49fde..3c92034cc32 100644--- a/src/features/WorkGallery/useOpenWork.ts+++ b/src/features/WorkGallery/useOpenWork.ts@@ -4,6 +4,7 @@ import { useCallback } from 'react';import { taskDetailPath } from '@/features/AgentTasks/shared/taskDetailPath';import { openArtboard } from '@/features/Artboard/openArtboard';import { openCanvasModal } from '@/features/CanvasModal/loader';+import { openCollectionModal } from '@/features/CollectionModal/loader';import { openDocumentModal } from '@/features/DocumentModal/loader';import { getWorkTypeDescriptor, isSafeExternalUrl } from '@/features/Work/descriptors';import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';@@ -44,6 +45,10 @@ export const useOpenWork = () => {window.open(openTarget.url, '_blank', 'noopener,noreferrer');return;}+ case 'collection': {+ void openCollectionModal(openTarget);+ return;+ }case 'task': {navigate(taskDetailPath(openTarget.identifier ?? openTarget.taskId, undefined, openTarget.name),