Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion apps/docs/content/docs/cli/reference.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -8604,7 +8604,7 @@ API request and response schemas: [getSourceCatalog](/api-reference/catalog/getS

### sim workflows source resources

List the tables, knowledge bases, credentials, workflows, skills, custom tools, MCP servers and env names source can name
List the tables, knowledge bases, credentials, workflows, skills, custom tools, MCP servers, files and env names source can name

```bash
sim workflows source resources
Expand Down
2 changes: 1 addition & 1 deletion apps/docs/content/docs/cli/workflows.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -1636,7 +1636,7 @@ Prints a builder in brief (an example call, the required params with types, the

Exit codes: 0 printed; 1 no builder or namespace of that name (the closest one is named), or no cached catalog (run a get once).

### List the tables, knowledge bases, credentials, workflows, skills, custom tools, MCP servers and env names source can name
### List the tables, knowledge bases, credentials, workflows, skills, custom tools, MCP servers, files and env names source can name

```bash
sim workflows source resources
Expand Down
2 changes: 1 addition & 1 deletion apps/docs/content/docs/workflows/code/directory.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ A resource's key is its file or folder name, and a workflow names it by that key
- `mcp/<key>.ts`: `export default defineMcpServer({ name?, url, headers?, auth?, timeout?, retries?, enabled? })`. A credential header holds `env.NAME` or `'Bearer {{NAME}}'`, never a literal secret; `stored()` keeps the value the server holds. A new host or path in `url` replaces the server; a new query string updates it in place. A workflow: `mcp('<key>').tool('<name>')`.
- `tables/<key>.ts`: `export default defineTable({ name, description?, folder?, columns: { … } })` with `column.string()`, `column.number()`, `column.select({ options: [...] })`, … from `@sim/workflow-sdk/workspace`. Rows stay out of source unless `rows` opts in: `{ mode: 'managed', key: '<unique column>' }` keeps the rows equal to `tables/<key>.rows.jsonl` (one JSON object per line, keyed by column key), `{ mode: 'seed' }` writes them once into a new table. A workflow: `table('<key>')`.
- `knowledge/<key>/knowledge.ts` (`defineKnowledgeBase({ name, description?, folder?, chunking?, embeddingModel? })`) and `knowledge/<key>/docs/`, one file per document, flat. A workflow: `knowledgeBase('<key>')`. Connector-synced documents are never part of source.
- `files/<path>`: every file is one workspace file at that folder path; no declaration.
- `files/<path>`: every file is one workspace file at that folder path; no declaration. A workflow: `file('<path>')` (the path under `files/`), as a file-upload field's value.
- `workflows/<key>/`: one workflow each, exactly a `sim workflows source get --dir` directory (`workflow.ts`, `functions/*`, `.sim/lock.json`, `.sim/base.json`).
- `deployments/<workflow key>.ts`: `defineDeployment({ live: 'draft' | 'pinned', api?: { public? }, chat? })` deploys `workflows/<workflow key>/`, so its schedule, webhook, API and chat triggers run. `live: 'draft'` publishes the draft whenever it differs from the live version; `'pinned'` never redeploys and says when the draft differs. A chat password is `env.NAME` (or `stored()` to keep the stored one); chat outputs name a block by its name. Removing the file undeploys the workflow (needs `--allow-delete`). Deploying needs workspace admin, never a workspace API key. MCP publishing is not part of source.

Expand Down
4 changes: 2 additions & 2 deletions apps/docs/content/docs/workflows/code/syntax.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -165,14 +165,14 @@ The optional third argument holds what belongs to the block, not to its settings

### Resource helpers

A key is the resource's stable key in the workspace; `.sim/sdk/workspace.d.ts` lists them. A key with no live resource is `E_MAT_UNKNOWN_RESOURCE` on apply.
A key is the resource's stable key in the workspace; `.sim/sdk/workspace.d.ts` lists them. A file's key is its folder path and name, so the same source names the file at that path in any workspace it is applied to. A key with no live resource is `E_MAT_UNKNOWN_RESOURCE` on apply.

| Form | Stands for |
| --- | --- |
| `credential('key')` | A saved credential |
| `table('key')` | A workspace table |
| `knowledgeBase('key')` | A knowledge base |
| `file('path')` | A workspace file |
| `file('folder/name.pdf')` | A workspace file, by its folder path and name; a file field's value, or an item of a multi-file field's list |
| `folder('key')` | A workspace folder |
| `childWorkflow('key')` | A workflow, for `runWorkflow`; `.asTool()` in a `tools` list |
| `customTool('key')` | A custom tool, in a `tools` list |
Expand Down
10 changes: 10 additions & 0 deletions apps/docs/openapi-v2-workflows.json
Original file line number Diff line number Diff line change
Expand Up @@ -6887,6 +6887,7 @@
"tools": ["create_issue", "list_issues"]
}
],
"files": ["contracts/acme.pdf"],
"env": ["CRM_KEY"],
"truncated": false
}
Expand Down Expand Up @@ -23925,6 +23926,13 @@
},
"description": "MCP servers, oldest first."
},
"files": {
"type": "array",
"items": {
"type": "string"
},
"description": "Workspace files by folder path and name (`docs/report.pdf`), each named in source as `file('docs/report.pdf')`, oldest upload first."
},
"env": {
"type": "array",
"items": {
Expand All @@ -23946,6 +23954,7 @@
"skills",
"customTools",
"mcpServers",
"files",
"env",
"truncated"
],
Expand Down Expand Up @@ -24029,6 +24038,7 @@
"tools": ["create_issue", "list_issues"]
}
],
"files": ["contracts/acme.pdf"],
"env": ["CRM_KEY"],
"truncated": false
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ const manifest = {
skills: [{ key: 'triage', id: 'skl_1', name: 'Triage' }],
customTools: [{ key: 'lookup-order', id: 'ctl_1', name: 'Lookup order' }],
mcpServers: [{ key: 'github', id: 'mcp-1', name: 'GitHub', tools: ['create_issue'] }],
files: ['contracts/acme.pdf'],
env: ['CRM_KEY'],
truncated: false,
}
Expand Down
1 change: 1 addition & 0 deletions apps/sim/lib/api/contracts/v2/openapi/source-resources.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ const SOURCE_RESOURCES_EXAMPLE = {
mcpServers: [
{ key: 'github', id: 'mcp-1a2b3c4d', name: 'GitHub', tools: ['create_issue', 'list_issues'] },
],
files: ['contracts/acme.pdf'],
env: ['CRM_KEY'],
truncated: false,
}
Expand Down
5 changes: 5 additions & 0 deletions apps/sim/lib/api/contracts/v2/source-resources.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,11 @@ const sourceResourcesSchema = z
.describe('An MCP server the workspace consumes: `mcp(key)`.')
)
.describe('MCP servers, oldest first.'),
files: z
.array(z.string())
.describe(
"Workspace files by folder path and name (`docs/report.pdf`), each named in source as `file('docs/report.pdf')`, oldest upload first."
),
env: z
.array(z.string())
.describe(
Expand Down
27 changes: 13 additions & 14 deletions apps/sim/lib/uploads/contexts/workspace/file-manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -767,9 +767,6 @@ export async function commitFileCreateInTx(
return inserted
}

/** Writes that commit with a new workspace file: run in its create transaction, given its id. */
export type WorkspaceFileCreateHook = (tx: DbTransaction, fileId: string) => Promise<void>

/**
* Upload a file to workspace-scoped storage
*/
Expand All @@ -785,11 +782,6 @@ export async function uploadWorkspaceFile(
exactName?: boolean
secretProvenance?: WorkspaceFileSecretProvenance
notifyWorkspaceChange?: boolean
/**
* Runs inside the create's transaction once the file row is inserted, so what it writes
* commits or rolls back with the file.
*/
withinCreate?: WorkspaceFileCreateHook
}
): Promise<UploadedWorkspaceFileRecord> {
logger.info(`Uploading workspace file: ${fileName} for workspace ${workspaceId}`)
Expand Down Expand Up @@ -867,7 +859,6 @@ export async function uploadWorkspaceFile(
secretProvenance: options?.secretProvenance,
})
const usage = await accounting.mutation.applyDelta(effectiveBuffer.length)
await options?.withinCreate?.(tx, inserted.id)
return { inserted, updatedUsage: usage, billing: accounting.billing }
})

Expand Down Expand Up @@ -2495,31 +2486,39 @@ async function listWorkspaceFileCandidates(
}

/**
* Live workspace files by id, by storage key, and by reference (resolved as
* Live workspace files by id, by storage key, by exact name in any folder (`names`, taken as
* written rather than as a VFS path), and by reference (resolved as
* {@link findListedWorkspaceFiles} resolves it), from one read and one folder-path hydration.
* `files` holds each match once, oldest upload first. Another workspace's ids and keys, deleted
* files, chat uploads, and owned files never match.
*/
export async function lookupActiveWorkspaceFiles(
workspaceId: string,
lookup: { ids: readonly string[]; keys: readonly string[]; references: readonly string[] }
lookup: {
ids: readonly string[]
keys: readonly string[]
names?: readonly string[]
references: readonly string[]
}
): Promise<{ files: WorkspaceFileRecord[]; references: Map<string, WorkspaceFileRecord | null> }> {
if (lookup.ids.length + lookup.keys.length + lookup.references.length === 0) {
const names = new Set(lookup.names)
if (lookup.ids.length + lookup.keys.length + names.size + lookup.references.length === 0) {
return { files: [], references: new Map() }
}
const byReference = referenceCandidates(lookup.references)
const candidates = await listWorkspaceFileCandidates(workspaceId, {
ids: [...lookup.ids, ...byReference.ids],
keys: lookup.keys,
leafNames: byReference.leafNames,
leafNames: [...byReference.leafNames, ...[...names].map(normalizeDisplaySegment)],
})
const references = resolveListedReferences(candidates, lookup.references)
const ids = new Set(lookup.ids)
const keys = new Set(lookup.keys)
const resolved = new Set([...references.values()].map((file) => file?.id))
return {
files: candidates.filter(
(file) => ids.has(file.id) || keys.has(file.key) || resolved.has(file.id)
(file) =>
ids.has(file.id) || keys.has(file.key) || names.has(file.name) || resolved.has(file.id)
),
references,
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import {
userTableDefinitions,
workspace,
workspaceEnvironment,
workspaceFiles,
} from '@sim/db/schema'
import { deleteWorkspaceFixture, insertWorkspaceFixture } from '@sim/db/testing/workspace-fixtures'
import {
Expand All @@ -34,6 +35,7 @@ import { featureFlagsMock, featureFlagsMockFns } from '@sim/testing/mocks/featur
import { generateId } from '@sim/utils/id'
import { eq, inArray } from 'drizzle-orm'
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest'
import { MAX_MANIFEST_RESOURCES_PER_KIND } from '@/lib/api/contracts/v2/source-resources'
import { readSourceResources } from '@/lib/workflows/application/read-source-resources'

vi.mock('@/lib/core/config/feature-flags', () => featureFlagsMock)
Expand Down Expand Up @@ -204,6 +206,16 @@ describe('source resources manifest', () => {
createdBy: tokenOwnerId,
},
])
await db.insert(workspaceFiles).values({
id: generateId(),
key: `workspace/${workspaceId}/plan.md`,
userId: adminId,
workspaceId,
context: 'workspace',
originalName: 'plan.md',
contentType: 'text/markdown',
sizeBytes: 7,
})
await db.insert(workspaceEnvironment).values({
id: generateId(),
workspaceId,
Expand Down Expand Up @@ -494,6 +506,21 @@ describe('source resources manifest', () => {
expect(manifest.tables.map((table) => table.name)).toEqual(['leads'])
})

it('lists workspace files by path, and omits them when the caller’s group hides the Files tab', async () => {
const visible = await readSourceResources.execute({
principal: session(readerId),
input: { workspaceId },
})
expect(visible.files).toEqual(['plan.md'])
await withholdInGroup({ hideFilesTab: true })
const manifest = await readSourceResources.execute({
principal: session(readerId),
input: { workspaceId },
})
expect(manifest.files).toEqual([])
expect(manifest.tables.map((table) => table.name)).toEqual(['leads'])
})

it('omits env names for a workspace API key, which the secrets listing denies', async () => {
const manifest = await readSourceResources.execute({
principal: workspaceKey(),
Expand All @@ -502,4 +529,36 @@ describe('source resources manifest', () => {
expect(manifest.env).toEqual([])
})
})

it('marks the files section truncated when a file no path names sits among the first page', async () => {
const before = Date.now() - 60 * 60 * 1000
const rows = Array.from({ length: MAX_MANIFEST_RESOURCES_PER_KIND + 1 }, (_, index) => ({
id: generateId(),
key: `workspace/${workspaceId}/bulk-${index}`,
userId: adminId,
workspaceId,
context: 'workspace',
originalName: index === 0 ? 'a/b.txt' : `bulk-${index}.txt`,
contentType: 'text/plain',
sizeBytes: 1,
uploadedAt: new Date(before + index),
}))
await db.insert(workspaceFiles).values(rows)
try {
const manifest = await readSourceResources.execute({
principal: session(adminId),
input: { workspaceId },
})
expect(manifest.files).toHaveLength(MAX_MANIFEST_RESOURCES_PER_KIND)
expect(manifest.files).not.toContain('plan.md')
expect(manifest.truncated).toBe(true)
} finally {
await db.delete(workspaceFiles).where(
inArray(
workspaceFiles.id,
rows.map((row) => row.id)
)
)
}
})
})
32 changes: 23 additions & 9 deletions apps/sim/lib/workflows/application/read-source-resources.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,11 @@ import type { StaticPermissionGroupCapability } from '@/lib/permission-groups/ca
import { isWorkspaceCapabilityWithheld } from '@/lib/permission-groups/capability-assertions'
import { isColumnType } from '@/lib/table/column-types'
import { workflowOperations } from '@/lib/workflows/application/operations'
import { loadEnvNames, loadVisibleCredentials } from '@/lib/workflows/code/resources'
import {
loadEnvNames,
loadVisibleCredentials,
loadWorkspaceFilePaths,
} from '@/lib/workflows/code/resources'
import { extractInputFieldsFromBlocks } from '@/lib/workflows/input-format'
import { INPUT_DEFINITION_TRIGGER_TYPES } from '@/lib/workflows/triggers/input-definition-triggers'
import { resolveActiveWorkspaceApplicationContext } from '@/lib/workspaces/application/context'
Expand Down Expand Up @@ -162,9 +166,9 @@ async function loadWorkflowInputs(
* Which manifest sections the caller may see, by the gates the editor's own pickers apply: env
* names follow the env-var autocomplete (the workspace environment read, `secrets.manage`, and
* like `secrets.list` never a workspace API key), credentials follow the credential selector
* (`integrations.manage`), and skills, custom tools, MCP servers, tables and knowledge bases
* follow their own lists (`skills.use`, `custom_tools.use`, `mcp_tools.use`, `tables.use`,
* `knowledge.use`). A withheld section is listed empty rather than refusing the whole manifest,
* (`integrations.manage`), and skills, custom tools, MCP servers, tables, knowledge bases and
* files follow their own lists (`skills.use`, `custom_tools.use`, `mcp_tools.use`, `tables.use`,
* `knowledge.use`, `files.use`). A withheld section is listed empty rather than refusing the whole manifest,
* so a member restricted from one still gets the workflows and the rest.
*/
async function visibleSections(principal: Principal, context: WorkspaceAuthorizationContext) {
Expand All @@ -185,6 +189,7 @@ async function visibleSections(principal: Principal, context: WorkspaceAuthoriza
// permission-group-enforced: mcp_tools.use — omits the MCP servers section, as the MCP server list refuses
// permission-group-enforced: tables.use — omits the tables section, as the table list refuses
// permission-group-enforced: knowledge.use — omits the knowledge bases section, as the knowledge base list refuses
// permission-group-enforced: files.use — omits the files section, as the file list refuses
const [
secretsWithheld,
integrationsWithheld,
Expand All @@ -193,6 +198,7 @@ async function visibleSections(principal: Principal, context: WorkspaceAuthoriza
mcpWithheld,
tablesWithheld,
knowledgeWithheld,
filesWithheld,
] = await Promise.all([
withheld('secrets.manage'),
withheld('integrations.manage'),
Expand All @@ -201,6 +207,7 @@ async function visibleSections(principal: Principal, context: WorkspaceAuthoriza
withheld('mcp_tools.use'),
withheld('tables.use'),
withheld('knowledge.use'),
withheld('files.use'),
])
return {
tables: !tablesWithheld,
Expand All @@ -210,6 +217,7 @@ async function visibleSections(principal: Principal, context: WorkspaceAuthoriza
skills: !skillsWithheld,
customTools: !customToolsWithheld,
mcpServers: !mcpWithheld,
files: !filesWithheld,
}
}

Expand All @@ -223,14 +231,15 @@ function capped<T>(rows: T[]): { rows: T[]; truncated: boolean } {
* The workspace resources a workflow file can name, by the keys source uses for them: tables
* with their columns, knowledge bases, saved credentials with their provider, workflows with
* the inputs their start block declares, workspace skills and custom tools, MCP servers with the
* tool names they list (best effort, see `loadMcpToolNames`), and env variable names (never
* values). Credentials are the ones the caller's credential listing shows, and every section is
* tool names they list (best effort, see `loadMcpToolNames`), workspace files by path, and env
Comment thread
waleedlatif1 marked this conversation as resolved.
Resolved
* variable names (never values). Credentials are the ones the caller's credential listing shows, and every section is
* omitted where the editor's own pickers or the resource's own list would withhold it (see
* `visibleSections`). The CLI writes it as
* `workspace.d.ts`, so `table('tickets')`, `skill('triage')` and `env.X` type-check.
*
* Every listed resource gets its key here (`resolveKeys` allocates one for a resource no source
* has named yet), so a key an agent reads from the manifest resolves on apply. That allocation is
* Every listed resource but a file (named by its path) gets its key here (`resolveKeys` allocates
* one for a resource no source has named yet), so a key an agent reads from the manifest resolves
* on apply. That allocation is
* idempotent identity bookkeeping, not a change to any resource, which is why a read-role caller
* (Copilot included) may cause it. Not audited, like the other catalog reads.
*/
Expand All @@ -256,6 +265,7 @@ export const readSourceResources = defineAuthorizedWorkspaceUseCase({
skillRows,
customToolRows,
mcpServerRows,
files,
env,
] = await Promise.all([
visible.tables
Expand Down Expand Up @@ -316,6 +326,9 @@ export const readSourceResources = defineAuthorizedWorkspaceUseCase({
.orderBy(asc(mcpServers.createdAt), asc(mcpServers.id))
.limit(PAGE)
: [],
visible.files
? loadWorkspaceFilePaths(workspaceId, MAX_MANIFEST_RESOURCES_PER_KIND)
: { paths: [], truncated: false },
visible.env ? loadEnvNames(workspaceId, userId, access) : [],
])

Expand Down Expand Up @@ -375,8 +388,9 @@ export const readSourceResources = defineAuthorizedWorkspaceUseCase({
const names = mcpTools.get(server.id)
return names ? { ...server, tools: names } : server
}),
files: files.paths,
env,
truncated: [tables, kbs, credentials, workflows, skills, tools, servers].some(
truncated: [tables, kbs, credentials, workflows, skills, tools, servers, files].some(
(section) => section.truncated
),
}
Expand Down
Loading
Loading