mirror of
https://github.com/windmill-labs/windmill.git
synced 2026-09-18 16:02:29 +00:00
Compare commits
8
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c2beda70df | ||
|
|
6649f1c520 | ||
|
|
967a7b1a8a | ||
|
|
e20cd87ef9 | ||
|
|
c297ed0052 | ||
|
|
4eab995cf7 | ||
|
|
381d4470ef | ||
|
|
e954d33613 |
@@ -1,5 +1,5 @@
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import type { BackendValidationSettings } from '../../core/backendValidation'
|
||||
import { buildWorkspaceId } from './workspaceId'
|
||||
|
||||
interface CompletedJobResultMaybe {
|
||||
completed: boolean
|
||||
@@ -24,7 +24,6 @@ export interface CompletedPreviewJob {
|
||||
const tokenCache = new Map<string, Promise<string>>()
|
||||
const sharedWorkspaceQueue = new Map<string, Promise<void>>()
|
||||
const managedSharedWorkspacePrefixes = ['f/evals/']
|
||||
const DEFAULT_WORKSPACE_PREFIX = 'ai-evals'
|
||||
|
||||
export class BackendPreviewClient {
|
||||
constructor(private readonly settings: BackendValidationSettings) {}
|
||||
@@ -441,16 +440,6 @@ async function withSharedWorkspaceLock<T>(workspaceId: string, body: () => Promi
|
||||
}
|
||||
}
|
||||
|
||||
function buildWorkspaceId(caseId: string, attempt: number): string {
|
||||
const caseSlug = caseId
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9-]+/g, '-')
|
||||
.replace(/^-+|-+$/g, '')
|
||||
.slice(0, 30)
|
||||
const suffix = randomUUID().slice(0, 8)
|
||||
return `${DEFAULT_WORKSPACE_PREFIX}-${caseSlug || 'case'}-a${attempt}-${suffix}`
|
||||
}
|
||||
|
||||
function extractFolderName(path: string): string | null {
|
||||
if (!path.startsWith('f/')) {
|
||||
return null
|
||||
|
||||
@@ -11,6 +11,7 @@ import type {
|
||||
Script
|
||||
} from '../../../frontend/src/lib/gen'
|
||||
import type {
|
||||
DataMetric,
|
||||
DataTableTables,
|
||||
DataTableTableSchema,
|
||||
EndpointTool,
|
||||
@@ -112,6 +113,9 @@ export interface BenchmarkWorkspaceRunnables {
|
||||
aiProviders?: BenchmarkWorkspaceAiProvider[]
|
||||
resources?: BenchmarkWorkspaceResource[]
|
||||
datatables?: BenchmarkDatatableSeed[]
|
||||
/** DuckLake catalog names, as `list_ducklakes` reports them. */
|
||||
ducklakes?: string[]
|
||||
dataMetrics?: DataMetric[]
|
||||
jobs?: BenchmarkWorkspaceJob[]
|
||||
}
|
||||
|
||||
@@ -673,6 +677,27 @@ export function listBenchmarkDatatables(workspace: string): DataTableTables[] |
|
||||
}))
|
||||
}
|
||||
|
||||
// ============= DuckLake catalogs and declared metrics =============
|
||||
|
||||
/** Seeded DuckLake names, or `null` for a non-benchmark workspace. */
|
||||
export function listBenchmarkDucklakes(workspace: string): string[] | null {
|
||||
const runnables = benchmarkWorkspaceRunnables.get(workspace)
|
||||
return runnables ? (runnables.ducklakes ?? []) : null
|
||||
}
|
||||
|
||||
/**
|
||||
* Seeded metric declarations, or `null` for a non-benchmark workspace.
|
||||
*
|
||||
* The `table` / `path_prefix` filters are ignored: which rows a filter selects is
|
||||
* `canonical_table_path`'s business and is pinned by `ducklakeTools.test.ts`.
|
||||
* Re-deriving it here would give the eval its own copy of that spec to drift from,
|
||||
* and the case this serves measures whether the model reaches for the tool at all.
|
||||
*/
|
||||
export function listBenchmarkDataMetrics(workspace: string): DataMetric[] | null {
|
||||
const runnables = benchmarkWorkspaceRunnables.get(workspace)
|
||||
return runnables ? (runnables.dataMetrics ?? []) : null
|
||||
}
|
||||
|
||||
export function getBenchmarkDatatableSchema(input: {
|
||||
workspace: string
|
||||
datatableName: string
|
||||
|
||||
@@ -76,7 +76,9 @@ vi.mock('$lib/gen', async () => {
|
||||
listBenchmarkPlainResources,
|
||||
listBenchmarkApps,
|
||||
listBenchmarkDatatables,
|
||||
listBenchmarkDataMetrics,
|
||||
listBenchmarkDrafts,
|
||||
listBenchmarkDucklakes,
|
||||
listBenchmarkFlows,
|
||||
listBenchmarkJobs,
|
||||
listBenchmarkScripts,
|
||||
@@ -341,6 +343,10 @@ vi.mock('$lib/gen', async () => {
|
||||
hasBenchmarkWorkspace(data.workspace)
|
||||
? (listBenchmarkDatatables(data.workspace) ?? [])
|
||||
: actual.WorkspaceService.listDataTableTables(data),
|
||||
listDucklakes: async (data: { workspace: string }) =>
|
||||
hasBenchmarkWorkspace(data.workspace)
|
||||
? (listBenchmarkDucklakes(data.workspace) ?? [])
|
||||
: actual.WorkspaceService.listDucklakes(data),
|
||||
getDataTableTableSchema: async (data: {
|
||||
workspace: string
|
||||
datatableName: string
|
||||
@@ -356,6 +362,12 @@ vi.mock('$lib/gen', async () => {
|
||||
})
|
||||
: actual.WorkspaceService.getDataTableTableSchema(data)
|
||||
}),
|
||||
DataMetricService: wrapService(actual.DataMetricService, {
|
||||
listDataMetrics: async (data: { workspace: string }) =>
|
||||
hasBenchmarkWorkspace(data.workspace)
|
||||
? { metrics: listBenchmarkDataMetrics(data.workspace) ?? [] }
|
||||
: actual.DataMetricService.listDataMetrics(data)
|
||||
}),
|
||||
ScheduleService: wrapService(actual.ScheduleService, {
|
||||
existsSchedule: async (data: { workspace: string; path: string }) =>
|
||||
hasBenchmarkWorkspace(data.workspace) ? false : actual.ScheduleService.existsSchedule(data),
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import type { WindmillBackendSettings } from "../../core/windmillBackendSettings";
|
||||
import { buildWorkspaceId } from "./workspaceId";
|
||||
|
||||
const tokenCache = new Map<string, Promise<string>>();
|
||||
const sharedWorkspaceQueue = new Map<string, Promise<void>>();
|
||||
const DEFAULT_WORKSPACE_PREFIX = "ai-evals";
|
||||
|
||||
export class WindmillBackendClient {
|
||||
constructor(private readonly settings: WindmillBackendSettings) {}
|
||||
@@ -179,16 +178,6 @@ async function withSharedWorkspaceLock<T>(
|
||||
}
|
||||
}
|
||||
|
||||
function buildWorkspaceId(caseId: string, attempt: number): string {
|
||||
const caseSlug = caseId
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9-]+/g, "-")
|
||||
.replace(/^-+|-+$/g, "")
|
||||
.slice(0, 30);
|
||||
const suffix = randomUUID().slice(0, 8);
|
||||
return `${DEFAULT_WORKSPACE_PREFIX}-${caseSlug || "case"}-a${attempt}-${suffix}`;
|
||||
}
|
||||
|
||||
async function expectOk(response: Response, context: string): Promise<void> {
|
||||
if (response.ok) {
|
||||
return;
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
import { describe, expect, it } from "bun:test";
|
||||
import { buildWorkspaceId } from "./workspaceId";
|
||||
|
||||
describe("buildWorkspaceId", () => {
|
||||
// `workspace.proper_id` rejects `--`, which a case id can carry itself and
|
||||
// which truncating a slug on a hyphen produces once the suffix adds its own.
|
||||
// One id per shape: cut landing on a hyphen, cut landing mid-word, no cut, and
|
||||
// a doubled hyphen no cut ever reaches.
|
||||
it("stays within the id length cap and the proper_id format", () => {
|
||||
for (const caseId of [
|
||||
"global-test6-secret-variable-draft",
|
||||
"global-test23-datatable-query-select",
|
||||
"short",
|
||||
"global--test-foo",
|
||||
]) {
|
||||
const id = buildWorkspaceId(caseId, 1);
|
||||
expect(id.length).toBeLessThanOrEqual(50);
|
||||
expect(id).toMatch(/^\w+(-\w+)*$/);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,22 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
|
||||
const DEFAULT_WORKSPACE_PREFIX = "ai-evals";
|
||||
|
||||
// A workspace id must be at most 50 characters AND match `^\w+(-\w+)*$`
|
||||
// (`workspace.proper_id`), so the case slug yields to the random suffix that
|
||||
// makes the id unique, and no hyphen may end up doubled — neither one already in
|
||||
// the case id nor one a truncation leaves for the suffix to follow.
|
||||
const MAX_WORKSPACE_ID_LENGTH = 50;
|
||||
|
||||
export function buildWorkspaceId(caseId: string, attempt: number): string {
|
||||
const caseSlug = caseId
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9-]+/g, "-")
|
||||
.replace(/-{2,}/g, "-")
|
||||
.replace(/^-+|-+$/g, "");
|
||||
const suffix = `-a${attempt}-${randomUUID().slice(0, 8)}`;
|
||||
const head = `${DEFAULT_WORKSPACE_PREFIX}-${caseSlug || "case"}`;
|
||||
return `${head
|
||||
.slice(0, MAX_WORKSPACE_ID_LENGTH - suffix.length)
|
||||
.replace(/-+$/, "")}${suffix}`;
|
||||
}
|
||||
+32
-12
@@ -1919,10 +1919,11 @@
|
||||
- when the lookup fails, tells the user instead of inventing table names
|
||||
- does not write scripts or resources to answer a read-only question
|
||||
|
||||
# --- API catalog (search_api_endpoints / call_api_get / call_api_endpoint) ---
|
||||
# The harness serves the catalog and the executed calls itself (mock
|
||||
# listMcpTools + benchmark fetch handlers in adapters/frontend), so these cases
|
||||
# do not require an mcp-enabled eval backend.
|
||||
# --- Dedicated tools preferred over the API catalog ---
|
||||
# The harness serves worker/queue reads itself (benchmark fetch handlers in
|
||||
# adapters/frontend), so these cases do not require an mcp-enabled eval backend.
|
||||
# The stale `api-catalog` in the id below is kept so results stay comparable
|
||||
# across benchmark runs.
|
||||
|
||||
- id: global-test30-api-catalog-workers
|
||||
prompt: |-
|
||||
@@ -1934,23 +1935,42 @@
|
||||
draftCountExactly: 0
|
||||
toolExpect:
|
||||
requiredToolsUsed:
|
||||
- search_api_endpoints
|
||||
- call_api_get
|
||||
- list_workers
|
||||
forbiddenToolsUsed:
|
||||
- call_api_get
|
||||
- call_api_endpoint
|
||||
- write_script
|
||||
- deploy_workspace_item
|
||||
toolCallArgs:
|
||||
- tool: call_api_get
|
||||
field: name
|
||||
stringIncludesAnyOf:
|
||||
- listWorkers
|
||||
# Read-only workspace inspection produces no draft; validate via tool use.
|
||||
skipJudge: true
|
||||
judgeChecklist:
|
||||
- discovers the workers endpoint through the API catalog instead of guessing or fabricating
|
||||
- reads worker state through list_workers instead of guessing or fabricating
|
||||
- reports worker status from the returned data
|
||||
|
||||
- id: global-test37-ducklake-declared-measure
|
||||
prompt: |-
|
||||
We track orders in the main ducklake. Write me a duckdb script that reports total
|
||||
revenue by month. Keep it as a draft, don't deploy it.
|
||||
initial: ai_evals/fixtures/frontend/global/initial/ducklake_orders_metrics.json
|
||||
runtime:
|
||||
maxTurns: 8
|
||||
validate:
|
||||
draftCountExactly: 1
|
||||
toolExpect:
|
||||
requiredToolsUsed:
|
||||
- list_data_metrics
|
||||
forbiddenToolsUsed:
|
||||
- deploy_workspace_item
|
||||
- delete_workspace_item
|
||||
# The judge runs: the point is not that the tool was called but that the number it
|
||||
# describes is the declared one. `revenue` excludes test rows, so an aggregate that
|
||||
# reproduces it without the filter is plausible, runnable and wrong.
|
||||
judgeChecklist:
|
||||
- totals revenue with the declared sum over the amount column rather than an invented aggregate over a guessed column
|
||||
- excludes test orders from the total, as the declared revenue measure does
|
||||
- groups by month using the declared order_month expression over order_date
|
||||
- does not introduce column names absent from the declarations
|
||||
|
||||
- id: global-test31-draft-test-run-not-deployed
|
||||
prompt: |-
|
||||
Update `f/evals/global/format_greeting` so the provided name is uppercased in the greeting, then run it with name "ada" to check it works.
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
{
|
||||
"workspace": {
|
||||
"ducklakes": ["main"],
|
||||
"dataMetrics": [
|
||||
{
|
||||
"script_path": "f/analytics/orders_pipeline",
|
||||
"table_path": "main/main.orders",
|
||||
"kind": "measure",
|
||||
"name": "revenue",
|
||||
"expr": "sum(amount)",
|
||||
"filter": "not is_test"
|
||||
},
|
||||
{
|
||||
"script_path": "f/analytics/orders_pipeline",
|
||||
"table_path": "main/main.orders",
|
||||
"kind": "measure",
|
||||
"name": "order_count",
|
||||
"expr": "count(*)"
|
||||
},
|
||||
{
|
||||
"script_path": "f/analytics/orders_pipeline",
|
||||
"table_path": "main/main.orders",
|
||||
"kind": "dimension",
|
||||
"name": "order_month",
|
||||
"expr": "date_trunc('month', order_date)"
|
||||
},
|
||||
{
|
||||
"script_path": "f/analytics/orders_pipeline",
|
||||
"table_path": "main/main.orders",
|
||||
"kind": "dimension",
|
||||
"name": "region",
|
||||
"expr": "region"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
+8
-2
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"db_name": "PostgreSQL",
|
||||
"query": "SELECT id, workspace_id, flow_path, title, created_at, updated_at, created_by\n FROM flow_conversation\n WHERE id = $1 AND workspace_id = $2\n FOR UPDATE",
|
||||
"query": "SELECT id, workspace_id, flow_path, title, created_at, updated_at, created_by, is_test\n FROM flow_conversation\n WHERE id = $1 AND workspace_id = $2",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
@@ -37,6 +37,11 @@
|
||||
"ordinal": 6,
|
||||
"name": "created_by",
|
||||
"type_info": "Varchar"
|
||||
},
|
||||
{
|
||||
"ordinal": 7,
|
||||
"name": "is_test",
|
||||
"type_info": "Bool"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
@@ -52,8 +57,9 @@
|
||||
true,
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
false
|
||||
]
|
||||
},
|
||||
"hash": "6f32c1feed096ff706ae359ad6a3ca33b3f82ca38289dfa4a69aa95041027d57"
|
||||
"hash": "48c8522a4fed219c5011f4ba63c81cfe028a8b2a32bd790840cef65c452a8c31"
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"db_name": "PostgreSQL",
|
||||
"query": "UPDATE flow_conversation SET title = $1, updated_at = updated_at\n WHERE id = $2 AND workspace_id = $3\n RETURNING id",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"ordinal": 0,
|
||||
"name": "id",
|
||||
"type_info": "Uuid"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Left": [
|
||||
"Varchar",
|
||||
"Uuid",
|
||||
"Text"
|
||||
]
|
||||
},
|
||||
"nullable": [
|
||||
false
|
||||
]
|
||||
},
|
||||
"hash": "5b9c9eb64051f291fed4be9bc0b0cc0aef2e7bde732899976eddac36a2da7658"
|
||||
}
|
||||
+10
-3
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"db_name": "PostgreSQL",
|
||||
"query": "INSERT INTO flow_conversation (id, workspace_id, flow_path, created_by, title)\n VALUES ($1, $2, $3, $4, $5)\n ON CONFLICT (id) DO NOTHING\n RETURNING id, workspace_id, flow_path, title, created_at, updated_at, created_by",
|
||||
"query": "INSERT INTO flow_conversation (id, workspace_id, flow_path, created_by, title, is_test)\n VALUES ($1, $2, $3, $4, $5, $6)\n ON CONFLICT (id) DO NOTHING\n RETURNING id, workspace_id, flow_path, title, created_at, updated_at, created_by, is_test",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
@@ -37,6 +37,11 @@
|
||||
"ordinal": 6,
|
||||
"name": "created_by",
|
||||
"type_info": "Varchar"
|
||||
},
|
||||
{
|
||||
"ordinal": 7,
|
||||
"name": "is_test",
|
||||
"type_info": "Bool"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
@@ -45,7 +50,8 @@
|
||||
"Varchar",
|
||||
"Varchar",
|
||||
"Varchar",
|
||||
"Varchar"
|
||||
"Varchar",
|
||||
"Bool"
|
||||
]
|
||||
},
|
||||
"nullable": [
|
||||
@@ -55,8 +61,9 @@
|
||||
true,
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
false
|
||||
]
|
||||
},
|
||||
"hash": "c1e3ed3ecc3bcb98f60ba8196d33fee4a74f61b061e5025ecb75882208b3ba8f"
|
||||
"hash": "6d259b8cce5da5fecefe4ce322789b6b2cc43b51f2056c677d58f39c31fb26cb"
|
||||
}
|
||||
+8
-2
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"db_name": "PostgreSQL",
|
||||
"query": "\n SELECT\n j.args as \"args: Json<HashMap<String, Box<RawValue>>>\",\n js.flow_status as \"flow_status: Json<windmill_common::flow_status::FlowStatus>\"\n FROM v2_job_status js\n INNER JOIN v2_job j ON j.id = js.id\n WHERE js.id = $1\n ",
|
||||
"query": "\n SELECT\n j.args as \"args: Json<HashMap<String, Box<RawValue>>>\",\n js.flow_status as \"flow_status: Json<windmill_common::flow_status::FlowStatus>\",\n j.runnable_path\n FROM v2_job_status js\n INNER JOIN v2_job j ON j.id = js.id\n WHERE js.id = $1\n ",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
@@ -12,6 +12,11 @@
|
||||
"ordinal": 1,
|
||||
"name": "flow_status: Json<windmill_common::flow_status::FlowStatus>",
|
||||
"type_info": "Jsonb"
|
||||
},
|
||||
{
|
||||
"ordinal": 2,
|
||||
"name": "runnable_path",
|
||||
"type_info": "Varchar"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
@@ -20,9 +25,10 @@
|
||||
]
|
||||
},
|
||||
"nullable": [
|
||||
true,
|
||||
true,
|
||||
true
|
||||
]
|
||||
},
|
||||
"hash": "dd89d652154748d6d7e625e31778f6885d0ee62d29a4b8894a4b459dd215a103"
|
||||
"hash": "9008f9abb70a9a07e38acb20bea6a710d0efd77dac4aedeb88d72240e816530b"
|
||||
}
|
||||
+8
-2
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"db_name": "PostgreSQL",
|
||||
"query": "SELECT id, workspace_id, flow_path, title, created_at, updated_at, created_by\n FROM flow_conversation\n WHERE id = $1 AND workspace_id = $2",
|
||||
"query": "SELECT id, workspace_id, flow_path, title, created_at, updated_at, created_by, is_test\n FROM flow_conversation\n WHERE id = $1 AND workspace_id = $2\n FOR UPDATE",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
@@ -37,6 +37,11 @@
|
||||
"ordinal": 6,
|
||||
"name": "created_by",
|
||||
"type_info": "Varchar"
|
||||
},
|
||||
{
|
||||
"ordinal": 7,
|
||||
"name": "is_test",
|
||||
"type_info": "Bool"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
@@ -52,8 +57,9 @@
|
||||
true,
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
false
|
||||
]
|
||||
},
|
||||
"hash": "c383cc023714b361d10c10e8fef1fc148ab1da942951ee9ffdddaecee76a6be9"
|
||||
"hash": "dd84f9dfb238d18cb74f9e43228345427131bf8008eba6920021d6a449791534"
|
||||
}
|
||||
Generated
+1
@@ -15665,6 +15665,7 @@ dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
"serde_yml",
|
||||
"sha1",
|
||||
"sha2 0.10.9",
|
||||
"size",
|
||||
"spki",
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
ALTER TABLE flow_conversation DROP COLUMN is_test;
|
||||
@@ -0,0 +1,26 @@
|
||||
-- A chat run from the flow editor's test panel is stored exactly like one from the
|
||||
-- deployed flow, so the two were indistinguishable once written. Marking them lets the
|
||||
-- lists tell a trial apart from a real conversation.
|
||||
ALTER TABLE flow_conversation ADD COLUMN is_test BOOLEAN NOT NULL DEFAULT false;
|
||||
|
||||
-- Existing rows: a conversation whose messages came from a flowpreview run was a test.
|
||||
-- Derived once here because the job is purged on retention, after which the origin of an
|
||||
-- old conversation is unknowable.
|
||||
--
|
||||
-- Walked to the root job rather than matched directly: an existing message row never holds
|
||||
-- the flow job itself. The rows point at the step that produced them — the AI agent's job
|
||||
-- for an answer, the tool's own job for a tool call — whose kind is never 'flowpreview'.
|
||||
--
|
||||
-- `root_job` first, matching `get_root_job_id` (windmill-worker/src/common.rs): only it
|
||||
-- reaches the top of the run. `flow_innermost_root_job` stops at the closest flow scope by
|
||||
-- design, so an agent inside a subflow would land on that subflow's 'flow' row and the
|
||||
-- conversation would read as deployed.
|
||||
UPDATE flow_conversation c
|
||||
SET is_test = true
|
||||
WHERE EXISTS (
|
||||
SELECT 1 FROM flow_conversation_message m
|
||||
JOIN v2_job j ON j.id = m.job_id
|
||||
JOIN v2_job root
|
||||
ON root.id = coalesce(j.root_job, j.flow_innermost_root_job, j.parent_job, j.id)
|
||||
WHERE m.conversation_id = c.id AND root.kind = 'flowpreview'
|
||||
);
|
||||
@@ -99,7 +99,7 @@ email_trigger: path(char), local_part(char), workspaced_local_part(bool), script
|
||||
favorite: usr(char), workspace_id(char), path(char), favorite_kind(favorite_kind)
|
||||
flow: workspace_id(char), path(char), summary(text), description(text), value(jsonb), edited_by(char), edited_at(ts), archived(bool), schema(json), extra_perms(jsonb), dependency_job(uuid), draft_only(bool), tag(char), ws_error_handler_muted(bool), dedicated_worker(bool), timeout(int), visible_to_runner_only(bool), concurrency_key(char), versions(bigint[]), on_behalf_of(varchar), on_behalf_of_email(text), lock_error_logs(text), labels(text[])
|
||||
FK: (workspace_id) -> workspace(id)
|
||||
flow_conversation: id(uuid), workspace_id(char), flow_path(char), title(char), created_at(ts), updated_at(ts), created_by(char)
|
||||
flow_conversation: id(uuid), workspace_id(char), flow_path(char), title(char), created_at(ts), updated_at(ts), created_by(char), is_test(bool)
|
||||
FK: (workspace_id) -> workspace(id)
|
||||
flow_conversation_message: id(uuid), conversation_id(uuid), message_type(message_type), content(text), job_id(uuid), created_at(ts), created_seq(int8), step_name(char), success(bool)
|
||||
FK: (conversation_id) -> flow_conversation(id) | (job_id) -> v2_job(id)
|
||||
|
||||
@@ -258,6 +258,7 @@ async fn test_new_turns_wait_for_conversation_cleanup_and_recreate(
|
||||
"test-user",
|
||||
"hi again",
|
||||
conv_id,
|
||||
false,
|
||||
)
|
||||
.await?;
|
||||
windmill_common::flow_conversations::add_message_to_conversation_tx(
|
||||
|
||||
@@ -78,17 +78,50 @@ impl Default for OutputType {
|
||||
#[serde(tag = "kind", rename_all = "lowercase")]
|
||||
pub enum Memory {
|
||||
Off,
|
||||
Auto {
|
||||
#[serde(default)]
|
||||
Window {
|
||||
#[serde(default, deserialize_with = "deserialize_null_as_zero")]
|
||||
context_length: usize,
|
||||
#[serde(default)]
|
||||
},
|
||||
/// Written before `window`. Its `memory_id` stays a fallback behind the run's memory id.
|
||||
Auto {
|
||||
#[serde(default, deserialize_with = "deserialize_null_as_zero")]
|
||||
context_length: usize,
|
||||
#[serde(default, deserialize_with = "deserialize_blank_as_none")]
|
||||
memory_id: Option<Uuid>,
|
||||
},
|
||||
/// Written before a step had history inputs of its own, and read on its own where it remains.
|
||||
Manual {
|
||||
messages: Vec<OpenAIMessage>,
|
||||
},
|
||||
}
|
||||
|
||||
// An editor form can leave `""` in a legacy baked id it never filled; it means no id rather than
|
||||
// failing every run of the step.
|
||||
fn deserialize_blank_as_none<'de, D: serde::Deserializer<'de>>(
|
||||
deserializer: D,
|
||||
) -> Result<Option<Uuid>, D::Error> {
|
||||
match <Option<String> as serde::Deserialize>::deserialize(deserializer)? {
|
||||
Some(id) if !id.trim().is_empty() => Uuid::parse_str(id.trim())
|
||||
.map(Some)
|
||||
.map_err(serde::de::Error::custom),
|
||||
_ => Ok(None),
|
||||
}
|
||||
}
|
||||
|
||||
// A count the editor's number field was cleared of is stored as `null`, which `default` does not
|
||||
// cover; it reads as 0, memory off, rather than failing every run of the step.
|
||||
fn deserialize_null_as_zero<'de, D: serde::Deserializer<'de>>(
|
||||
deserializer: D,
|
||||
) -> Result<usize, D::Error> {
|
||||
<Option<usize> as serde::Deserialize>::deserialize(deserializer).map(Option::unwrap_or_default)
|
||||
}
|
||||
|
||||
fn deserialize_present<'de, D: serde::Deserializer<'de>>(
|
||||
deserializer: D,
|
||||
) -> Result<Option<serde_json::Value>, D::Error> {
|
||||
<serde_json::Value as serde::Deserialize>::deserialize(deserializer).map(Some)
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct AIAgentArgsRaw {
|
||||
provider: ProviderWithResource,
|
||||
@@ -103,6 +136,12 @@ struct AIAgentArgsRaw {
|
||||
streaming: Option<bool>,
|
||||
max_iterations: Option<usize>,
|
||||
memory: Option<Memory>,
|
||||
// A null must stay distinguishable from an absent key: a step whose own memory id evaluates to
|
||||
// nothing runs stateless instead of falling back to the run's memory id.
|
||||
#[serde(default, deserialize_with = "deserialize_present")]
|
||||
memory_id: Option<serde_json::Value>,
|
||||
#[serde(default)]
|
||||
previous_messages: Option<Vec<OpenAIMessage>>,
|
||||
enabled_tools: Option<Vec<String>>,
|
||||
// Legacy field for backward compatibility
|
||||
messages_context_length: Option<usize>,
|
||||
@@ -124,6 +163,10 @@ pub struct AIAgentArgs {
|
||||
pub streaming: Option<bool>,
|
||||
pub max_iterations: Option<usize>,
|
||||
pub memory: Option<Memory>,
|
||||
/// Memory id set on the step, overriding the run's. Empty when its expression produced none.
|
||||
pub memory_id: Option<String>,
|
||||
/// History supplied by the flow, replayed without reading or writing memory.
|
||||
pub previous_messages: Option<Vec<OpenAIMessage>>,
|
||||
/// Which of the agent's tools this run may call; `narrow_roster` holds what the names are and
|
||||
/// what `None` means.
|
||||
pub enabled_tools: Option<Vec<String>>,
|
||||
@@ -139,12 +182,17 @@ impl From<AIAgentArgsRaw> for AIAgentArgs {
|
||||
});
|
||||
|
||||
// Backward compatibility: if context_length is 0, use off mode
|
||||
let memory = memory.map(|memory| {
|
||||
if let Memory::Auto { context_length: 0, .. } = memory {
|
||||
let memory = memory.map(|memory| match memory {
|
||||
Memory::Auto { context_length: 0, .. } | Memory::Window { context_length: 0 } => {
|
||||
Memory::Off
|
||||
} else {
|
||||
memory
|
||||
}
|
||||
memory => memory,
|
||||
});
|
||||
|
||||
let memory_id = raw.memory_id.map(|value| match value {
|
||||
serde_json::Value::Null => String::new(),
|
||||
serde_json::Value::String(s) => s.trim().to_string(),
|
||||
value => value.to_string(),
|
||||
});
|
||||
|
||||
AIAgentArgs {
|
||||
@@ -159,6 +207,8 @@ impl From<AIAgentArgsRaw> for AIAgentArgs {
|
||||
streaming: raw.streaming,
|
||||
max_iterations: raw.max_iterations,
|
||||
memory,
|
||||
memory_id,
|
||||
previous_messages: raw.previous_messages,
|
||||
enabled_tools: raw.enabled_tools,
|
||||
credentials_check: raw.credentials_check.unwrap_or(false),
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use axum::{
|
||||
extract::{Path, Query},
|
||||
routing::{delete, get},
|
||||
routing::{delete, get, post},
|
||||
Extension, Json, Router,
|
||||
};
|
||||
use chrono::{DateTime, Utc};
|
||||
@@ -15,13 +15,14 @@ use windmill_common::{
|
||||
db::{UserDB, DB},
|
||||
error::{JsonResult, Result},
|
||||
flow_conversations::MessageType,
|
||||
utils::{not_found_if_none, paginate, Pagination},
|
||||
utils::{not_found_if_none, paginate, truncate_with_ellipsis, Pagination},
|
||||
};
|
||||
|
||||
pub fn workspaced_service() -> Router {
|
||||
Router::new()
|
||||
.route("/list", get(list_conversations))
|
||||
.route("/delete/{conversation_id}", delete(delete_conversation))
|
||||
.route("/update/{conversation_id}", post(update_conversation))
|
||||
.route("/{conversation_id}/messages", get(list_messages))
|
||||
}
|
||||
|
||||
@@ -38,9 +39,22 @@ pub struct FlowConversationMessage {
|
||||
pub success: bool,
|
||||
}
|
||||
|
||||
/// Which conversations a listing holds. A test chat was started from the editor's test
|
||||
/// panel; a deployed one from the flow itself.
|
||||
#[derive(Deserialize, Default, Clone, Copy)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum ConversationKind {
|
||||
Test,
|
||||
/// The default: a deployed flow's chat should not surface someone's trial runs.
|
||||
#[default]
|
||||
Deployed,
|
||||
All,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct ListConversationsQuery {
|
||||
pub flow_path: Option<String>,
|
||||
pub kind: Option<ConversationKind>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
@@ -67,6 +81,7 @@ async fn list_conversations(
|
||||
"created_at",
|
||||
"updated_at",
|
||||
"created_by",
|
||||
"is_test",
|
||||
])
|
||||
.and_where_eq("workspace_id", "?".bind(&w_id));
|
||||
|
||||
@@ -74,6 +89,16 @@ async fn list_conversations(
|
||||
sqlb.and_where_eq("flow_path", "?".bind(flow_path));
|
||||
}
|
||||
|
||||
match query.kind.unwrap_or_default() {
|
||||
ConversationKind::Test => {
|
||||
sqlb.and_where_eq("is_test", "true");
|
||||
}
|
||||
ConversationKind::Deployed => {
|
||||
sqlb.and_where_eq("is_test", "false");
|
||||
}
|
||||
ConversationKind::All => {}
|
||||
}
|
||||
|
||||
sqlb.order_by("updated_at", true)
|
||||
.limit(per_page as i64)
|
||||
.offset(offset as i64);
|
||||
@@ -101,7 +126,7 @@ async fn delete_conversation(
|
||||
// Verify the conversation exists and belongs to the user
|
||||
let conversation = sqlx::query_as!(
|
||||
FlowConversation,
|
||||
"SELECT id, workspace_id, flow_path, title, created_at, updated_at, created_by
|
||||
"SELECT id, workspace_id, flow_path, title, created_at, updated_at, created_by, is_test
|
||||
FROM flow_conversation
|
||||
WHERE id = $1 AND workspace_id = $2",
|
||||
conversation_id,
|
||||
@@ -148,6 +173,50 @@ async fn delete_conversation(
|
||||
Ok(format!("Conversation {} deleted", conversation_id))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct UpdateConversation {
|
||||
pub title: String,
|
||||
}
|
||||
|
||||
async fn update_conversation(
|
||||
authed: ApiAuthed,
|
||||
Extension(user_db): Extension<UserDB>,
|
||||
Path((w_id, conversation_id)): Path<(String, Uuid)>,
|
||||
Json(update): Json<UpdateConversation>,
|
||||
) -> Result<String> {
|
||||
// Postgres refuses a NUL in a text column, so it must not reach the query as a 500.
|
||||
if update.title.contains('\0') {
|
||||
return Err(windmill_common::error::Error::BadRequest(
|
||||
"title cannot contain a NUL character".to_string(),
|
||||
));
|
||||
}
|
||||
// The column is VARCHAR(255) and the helper appends an ellipsis to what it cuts, so the
|
||||
// bound it takes is three short of the column's. A longer title would otherwise reach
|
||||
// Postgres as a 22001 and come back a 500.
|
||||
let title = truncate_with_ellipsis(update.title.trim(), 252);
|
||||
|
||||
let mut tx = user_db.clone().begin(&authed).await?;
|
||||
|
||||
// `updated_at` is kept: the list is ordered by it, and a rename must not move the
|
||||
// chat to the top the way a new turn does.
|
||||
let updated = sqlx::query_scalar!(
|
||||
"UPDATE flow_conversation SET title = $1, updated_at = updated_at
|
||||
WHERE id = $2 AND workspace_id = $3
|
||||
RETURNING id",
|
||||
title,
|
||||
conversation_id,
|
||||
&w_id
|
||||
)
|
||||
.fetch_optional(&mut *tx)
|
||||
.await?;
|
||||
|
||||
not_found_if_none(updated, "Conversation", conversation_id.to_string())?;
|
||||
|
||||
tx.commit().await?;
|
||||
|
||||
Ok(format!("Conversation {} updated", conversation_id))
|
||||
}
|
||||
|
||||
async fn list_messages(
|
||||
authed: ApiAuthed,
|
||||
Extension(user_db): Extension<UserDB>,
|
||||
|
||||
@@ -653,9 +653,11 @@ pub async fn set_flow_memory_id(
|
||||
pub async fn process_flow_run_query_params(
|
||||
tx: &mut sqlx::Transaction<'_, sqlx::Postgres>,
|
||||
job_id: Uuid,
|
||||
w_id: &str,
|
||||
flow_path: &str,
|
||||
run_query: &RunJobQuery,
|
||||
) -> error::Result<()> {
|
||||
if let Some(memory_id) = run_query.memory_id {
|
||||
if let Some(memory_id) = run_query.memory_key(w_id, flow_path) {
|
||||
set_flow_memory_id(tx, job_id, memory_id).await?;
|
||||
}
|
||||
Ok(())
|
||||
@@ -669,10 +671,11 @@ pub async fn handle_chat_conversation_messages(
|
||||
run_query: &RunJobQuery,
|
||||
user_message_raw: Option<&Box<serde_json::value::RawValue>>,
|
||||
job_id: Uuid,
|
||||
is_test: bool,
|
||||
) -> error::Result<()> {
|
||||
// Names the query parameter rather than the field: it is not a flow argument, and
|
||||
// supplying it as one is the first thing tried on reading `memory_id is required`.
|
||||
let memory_id = run_query.memory_id.ok_or_else(|| {
|
||||
let memory_id = run_query.memory_key(w_id, flow_path).ok_or_else(|| {
|
||||
windmill_common::error::Error::BadRequest(
|
||||
"memory_id is required for chat-enabled flows. Pass it as the `memory_id` query \
|
||||
parameter, not as a flow argument: it names the conversation the turn belongs to, \
|
||||
@@ -701,6 +704,7 @@ pub async fn handle_chat_conversation_messages(
|
||||
&authed.username,
|
||||
&user_message,
|
||||
memory_id,
|
||||
is_test,
|
||||
)
|
||||
.await?;
|
||||
|
||||
@@ -822,7 +826,7 @@ pub async fn run_flow<'c>(
|
||||
.await?;
|
||||
|
||||
// Set memory_id if provided (for agent memory)
|
||||
if let Some(memory_id) = run_query.memory_id {
|
||||
if let Some(memory_id) = run_query.memory_key(w_id, flow_path) {
|
||||
set_flow_memory_id(&mut tx, uuid, memory_id).await?;
|
||||
}
|
||||
|
||||
@@ -836,6 +840,7 @@ pub async fn run_flow<'c>(
|
||||
&run_query,
|
||||
args.args.get("user_message"),
|
||||
uuid,
|
||||
false,
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
|
||||
@@ -47,13 +47,25 @@ pub struct RunJobQuery {
|
||||
pub cache_ignore_s3_path: Option<bool>,
|
||||
pub skip_preprocessor: Option<bool>,
|
||||
pub poll_delay_ms: Option<u64>,
|
||||
pub memory_id: Option<Uuid>,
|
||||
/// Any string; see [`RunJobQuery::memory_key`].
|
||||
pub memory_id: Option<String>,
|
||||
pub trigger_external_id: Option<String>,
|
||||
pub service_name: Option<String>,
|
||||
pub suspended_mode: Option<bool>,
|
||||
}
|
||||
|
||||
impl RunJobQuery {
|
||||
/// The memory id as stored in `flow_status.memory_id`: a uuid is kept, any other string hashed
|
||||
/// within the workspace and the flow being run.
|
||||
pub fn memory_key(&self, workspace_id: &str, flow_path: &str) -> Option<Uuid> {
|
||||
self.memory_id
|
||||
.as_deref()
|
||||
.filter(|memory_id| !memory_id.trim().is_empty())
|
||||
.map(|memory_id| {
|
||||
windmill_common::flow_conversations::memory_key(workspace_id, flow_path, memory_id)
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn get_scheduled_for(
|
||||
&self,
|
||||
db: &DB,
|
||||
|
||||
@@ -11267,11 +11267,10 @@ paths:
|
||||
- $ref: "#/components/parameters/NewJobId"
|
||||
- $ref: "#/components/parameters/SkipPreprocessor"
|
||||
- name: memory_id
|
||||
description: memory ID for chat-enabled flows
|
||||
description: Memory id for the flow's AI agent steps. A uuid is used as is; any other string is hashed within the workspace and flow, so the same string always names the same memory of that flow.
|
||||
in: query
|
||||
schema:
|
||||
type: string
|
||||
format: uuid
|
||||
|
||||
requestBody:
|
||||
description: script args
|
||||
@@ -11308,11 +11307,10 @@ paths:
|
||||
- $ref: "#/components/parameters/NewJobId"
|
||||
- $ref: "#/components/parameters/SkipPreprocessor"
|
||||
- name: memory_id
|
||||
description: memory ID for chat-enabled flows
|
||||
description: Memory id for the flow's AI agent steps. A uuid is used as is; any other string is hashed within the workspace and flow, so the same string always names the same memory of that flow.
|
||||
in: query
|
||||
schema:
|
||||
type: string
|
||||
format: uuid
|
||||
|
||||
requestBody:
|
||||
description: script args
|
||||
@@ -11349,11 +11347,10 @@ paths:
|
||||
- $ref: "#/components/parameters/NewJobId"
|
||||
- $ref: "#/components/parameters/SkipPreprocessor"
|
||||
- name: memory_id
|
||||
description: memory ID for chat-enabled flows
|
||||
description: Memory id for the flow's AI agent steps. A uuid is used as is; any other string is hashed within the workspace and flow, so the same string always names the same memory of that flow.
|
||||
in: query
|
||||
schema:
|
||||
type: string
|
||||
format: uuid
|
||||
|
||||
responses:
|
||||
"200":
|
||||
@@ -11376,11 +11373,10 @@ paths:
|
||||
- $ref: "#/components/parameters/NewJobId"
|
||||
- $ref: "#/components/parameters/SkipPreprocessor"
|
||||
- name: memory_id
|
||||
description: memory ID for chat-enabled flows
|
||||
description: Memory id for the flow's AI agent steps. A uuid is used as is; any other string is hashed within the workspace and flow, so the same string always names the same memory of that flow.
|
||||
in: query
|
||||
schema:
|
||||
type: string
|
||||
format: uuid
|
||||
- name: poll_delay_ms
|
||||
description: delay between polling for job updates in milliseconds
|
||||
in: query
|
||||
@@ -11418,11 +11414,10 @@ paths:
|
||||
- $ref: "#/components/parameters/NewJobId"
|
||||
- $ref: "#/components/parameters/SkipPreprocessor"
|
||||
- name: memory_id
|
||||
description: memory ID for chat-enabled flows
|
||||
description: Memory id for the flow's AI agent steps. A uuid is used as is; any other string is hashed within the workspace and flow, so the same string always names the same memory of that flow.
|
||||
in: query
|
||||
schema:
|
||||
type: string
|
||||
format: uuid
|
||||
- name: poll_delay_ms
|
||||
description: delay between polling for job updates in milliseconds
|
||||
in: query
|
||||
@@ -11458,11 +11453,10 @@ paths:
|
||||
- $ref: "#/components/parameters/NewJobId"
|
||||
- $ref: "#/components/parameters/SkipPreprocessor"
|
||||
- name: memory_id
|
||||
description: memory ID for chat-enabled flows
|
||||
description: Memory id for the flow's AI agent steps. A uuid is used as is; any other string is hashed within the workspace and flow, so the same string always names the same memory of that flow.
|
||||
in: query
|
||||
schema:
|
||||
type: string
|
||||
format: uuid
|
||||
- name: poll_delay_ms
|
||||
description: delay between polling for job updates in milliseconds
|
||||
in: query
|
||||
@@ -11506,11 +11500,10 @@ paths:
|
||||
- $ref: "#/components/parameters/NewJobId"
|
||||
- $ref: "#/components/parameters/SkipPreprocessor"
|
||||
- name: memory_id
|
||||
description: memory ID for chat-enabled flows
|
||||
description: Memory id for the flow's AI agent steps. A uuid is used as is; any other string is hashed within the workspace and flow, so the same string always names the same memory of that flow.
|
||||
in: query
|
||||
schema:
|
||||
type: string
|
||||
format: uuid
|
||||
- name: poll_delay_ms
|
||||
description: delay between polling for job updates in milliseconds
|
||||
in: query
|
||||
@@ -12464,6 +12457,15 @@ paths:
|
||||
in: query
|
||||
schema:
|
||||
type: string
|
||||
- name: kind
|
||||
description: which conversations to list - the flow editor's test chats, the deployed flow's own (the default), or both
|
||||
in: query
|
||||
schema:
|
||||
type: string
|
||||
enum:
|
||||
- test
|
||||
- deployed
|
||||
- all
|
||||
responses:
|
||||
"200":
|
||||
description: flow conversations list
|
||||
@@ -12474,6 +12476,40 @@ paths:
|
||||
items:
|
||||
$ref: "#/components/schemas/FlowConversation"
|
||||
|
||||
/w/{workspace}/flow_conversations/update/{conversation_id}:
|
||||
post:
|
||||
summary: rename flow conversation
|
||||
operationId: updateFlowConversation
|
||||
tags:
|
||||
- flow_conversations
|
||||
parameters:
|
||||
- $ref: "#/components/parameters/WorkspaceId"
|
||||
- name: conversation_id
|
||||
description: conversation id
|
||||
in: path
|
||||
required: true
|
||||
schema:
|
||||
type: string
|
||||
format: uuid
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
required: [title]
|
||||
properties:
|
||||
title:
|
||||
type: string
|
||||
description: the chat's name
|
||||
responses:
|
||||
"200":
|
||||
description: flow conversation updated
|
||||
content:
|
||||
text/plain:
|
||||
schema:
|
||||
type: string
|
||||
|
||||
/w/{workspace}/flow_conversations/delete/{conversation_id}:
|
||||
delete:
|
||||
summary: delete flow conversation
|
||||
@@ -14868,11 +14904,10 @@ paths:
|
||||
schema:
|
||||
type: boolean
|
||||
- name: memory_id
|
||||
description: memory ID for chat-enabled flows
|
||||
description: Memory id for the flow's AI agent steps. A uuid is used as is; any other string is hashed within the workspace and flow, so the same string always names the same memory of that flow.
|
||||
in: query
|
||||
schema:
|
||||
type: string
|
||||
format: uuid
|
||||
requestBody:
|
||||
description: flow args
|
||||
required: true
|
||||
@@ -14926,11 +14961,10 @@ paths:
|
||||
schema:
|
||||
type: boolean
|
||||
- name: memory_id
|
||||
description: memory ID for chat-enabled flows
|
||||
description: Memory id for the flow's AI agent steps. A uuid is used as is; any other string is hashed within the workspace and flow, so the same string always names the same memory of that flow.
|
||||
in: query
|
||||
schema:
|
||||
type: string
|
||||
format: uuid
|
||||
requestBody:
|
||||
description: flow args
|
||||
required: true
|
||||
@@ -15418,11 +15452,10 @@ paths:
|
||||
type: boolean
|
||||
- $ref: "#/components/parameters/NewJobId"
|
||||
- name: memory_id
|
||||
description: memory ID for chat-enabled flows
|
||||
description: Memory id for the flow's AI agent steps. A uuid is used as is; any other string is hashed within the workspace and flow, so the same string always names the same memory of that flow.
|
||||
in: query
|
||||
schema:
|
||||
type: string
|
||||
format: uuid
|
||||
|
||||
requestBody:
|
||||
description: preview
|
||||
@@ -15450,11 +15483,10 @@ paths:
|
||||
parameters:
|
||||
- $ref: "#/components/parameters/WorkspaceId"
|
||||
- name: memory_id
|
||||
description: memory ID for chat-enabled flows
|
||||
description: Memory id for the flow's AI agent steps. A uuid is used as is; any other string is hashed within the workspace and flow, so the same string always names the same memory of that flow.
|
||||
in: query
|
||||
schema:
|
||||
type: string
|
||||
format: uuid
|
||||
|
||||
requestBody:
|
||||
description: preview
|
||||
@@ -28301,7 +28333,7 @@ components:
|
||||
FlowConversation:
|
||||
type: object
|
||||
required:
|
||||
[id, workspace_id, flow_path, created_at, updated_at, created_by]
|
||||
[id, workspace_id, flow_path, created_at, updated_at, created_by, is_test]
|
||||
properties:
|
||||
id:
|
||||
type: string
|
||||
@@ -28328,6 +28360,9 @@ components:
|
||||
created_by:
|
||||
type: string
|
||||
description: Username who created the conversation
|
||||
is_test:
|
||||
type: boolean
|
||||
description: Started from the flow editor's test panel rather than a deployed run
|
||||
|
||||
FlowConversationMessage:
|
||||
type: object
|
||||
|
||||
@@ -4310,11 +4310,11 @@ async fn execute_component(
|
||||
}
|
||||
}
|
||||
|
||||
let is_flow = payload
|
||||
let flow_path = payload
|
||||
.path
|
||||
.as_ref()
|
||||
.map(|p| p.starts_with("flow/"))
|
||||
.unwrap_or(false);
|
||||
.as_deref()
|
||||
.and_then(|path| path.strip_prefix("flow/"))
|
||||
.map(str::to_string);
|
||||
|
||||
// Tag for inline-script jobs is read from the deployed policy in run mode;
|
||||
// only preview mode (editor) honors the client-supplied tag. This applies to
|
||||
@@ -4444,8 +4444,9 @@ async fn execute_component(
|
||||
|
||||
// Apply runnable query parameters if provided
|
||||
if let Some(ref run_query) = payload.run_query_params {
|
||||
if is_flow {
|
||||
crate::jobs::process_flow_run_query_params(&mut tx, uuid, run_query).await?;
|
||||
if let Some(flow_path) = flow_path.as_deref() {
|
||||
crate::jobs::process_flow_run_query_params(&mut tx, uuid, &w_id, flow_path, run_query)
|
||||
.await?;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -9540,7 +9540,7 @@ async fn run_preview_flow_job(
|
||||
.await?;
|
||||
|
||||
// Set memory_id if provided (for agent memory)
|
||||
if let Some(memory_id) = run_query.memory_id {
|
||||
if let Some(memory_id) = run_query.memory_key(&w_id, &flow_path) {
|
||||
set_flow_memory_id(&mut tx, uuid, memory_id).await?;
|
||||
}
|
||||
|
||||
@@ -9554,6 +9554,8 @@ async fn run_preview_flow_job(
|
||||
&run_query,
|
||||
user_message.as_ref(),
|
||||
uuid,
|
||||
// Run from the editor's test panel: a trial, not a real conversation.
|
||||
true,
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
|
||||
@@ -33,6 +33,7 @@ path = "src/lib.rs"
|
||||
tar.workspace = true
|
||||
hmac.workspace = true
|
||||
sha2.workspace = true
|
||||
sha1.workspace = true
|
||||
thiserror.workspace = true
|
||||
anyhow.workspace = true
|
||||
serde.workspace = true
|
||||
|
||||
@@ -7,6 +7,29 @@ use crate::db::DB;
|
||||
use crate::error::Result;
|
||||
use crate::utils::truncate_with_ellipsis;
|
||||
|
||||
/// Changing it detaches every memory stored under a string memory id.
|
||||
const MEMORY_ID_NAMESPACE: Uuid = Uuid::from_u128(0x6f1c2d4e_8a3b_5c7d_9e0f_1a2b3c4d5e6f);
|
||||
|
||||
/// Memory is stored and carried in `flow_status.memory_id` as a uuid, which names the same memory
|
||||
/// wherever it is passed, as a chat conversation id must. Any other string names a memory through a
|
||||
/// name-based (v5) uuid scoped to its workspace and flow, so the same key in two flows or two
|
||||
/// workspaces names two memories, and chat conversation ids stay unique across workspaces.
|
||||
pub fn memory_key(workspace_id: &str, flow_path: &str, memory_id: &str) -> Uuid {
|
||||
let memory_id = memory_id.trim();
|
||||
Uuid::parse_str(memory_id).unwrap_or_else(|_| {
|
||||
use sha1::{Digest, Sha1};
|
||||
let mut hasher = Sha1::new();
|
||||
hasher.update(MEMORY_ID_NAMESPACE.as_bytes());
|
||||
for part in [workspace_id, flow_path, memory_id] {
|
||||
hasher.update(part.as_bytes());
|
||||
hasher.update([0u8]);
|
||||
}
|
||||
let mut bytes = [0u8; 16];
|
||||
bytes.copy_from_slice(&hasher.finalize()[..16]);
|
||||
uuid::Builder::from_sha1_bytes(bytes).into_uuid()
|
||||
})
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, sqlx::Type)]
|
||||
#[sqlx(type_name = "MESSAGE_TYPE", rename_all = "lowercase")]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
@@ -26,8 +49,12 @@ pub struct FlowConversation {
|
||||
pub created_at: DateTime<Utc>,
|
||||
pub updated_at: DateTime<Utc>,
|
||||
pub created_by: String,
|
||||
/// Started from the flow editor's test panel rather than a deployed run.
|
||||
pub is_test: bool,
|
||||
}
|
||||
|
||||
/// `is_test` is written on insert. An existing conversation of the other kind refuses the
|
||||
/// turn, so preview and deployed runs never share one.
|
||||
pub async fn get_or_create_conversation_with_id(
|
||||
tx: &mut sqlx::Transaction<'_, sqlx::Postgres>,
|
||||
w_id: &str,
|
||||
@@ -35,9 +62,10 @@ pub async fn get_or_create_conversation_with_id(
|
||||
username: &str,
|
||||
title: &str,
|
||||
conversation_id: Uuid,
|
||||
is_test: bool,
|
||||
) -> Result<FlowConversation> {
|
||||
if let Some(existing) = lock_conversation(tx, w_id, conversation_id).await? {
|
||||
return Ok(existing);
|
||||
return same_kind(existing, is_test);
|
||||
}
|
||||
|
||||
// Truncate title to 25 characters max
|
||||
@@ -47,15 +75,16 @@ pub async fn get_or_create_conversation_with_id(
|
||||
// wins, the others wait on it, do nothing, and read the row it created.
|
||||
let created = sqlx::query_as!(
|
||||
FlowConversation,
|
||||
"INSERT INTO flow_conversation (id, workspace_id, flow_path, created_by, title)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
"INSERT INTO flow_conversation (id, workspace_id, flow_path, created_by, title, is_test)
|
||||
VALUES ($1, $2, $3, $4, $5, $6)
|
||||
ON CONFLICT (id) DO NOTHING
|
||||
RETURNING id, workspace_id, flow_path, title, created_at, updated_at, created_by",
|
||||
RETURNING id, workspace_id, flow_path, title, created_at, updated_at, created_by, is_test",
|
||||
conversation_id,
|
||||
w_id,
|
||||
flow_path,
|
||||
username,
|
||||
title
|
||||
title,
|
||||
is_test
|
||||
)
|
||||
.fetch_optional(&mut **tx)
|
||||
.await?;
|
||||
@@ -63,13 +92,29 @@ pub async fn get_or_create_conversation_with_id(
|
||||
return Ok(conversation);
|
||||
}
|
||||
|
||||
lock_conversation(tx, w_id, conversation_id)
|
||||
// The concurrent first turn that won the insert may have been of the other kind.
|
||||
let existing = lock_conversation(tx, w_id, conversation_id)
|
||||
.await?
|
||||
.ok_or_else(|| {
|
||||
crate::error::Error::BadRequest(format!(
|
||||
"conversation {conversation_id} belongs to another workspace"
|
||||
))
|
||||
})
|
||||
})?;
|
||||
same_kind(existing, is_test)
|
||||
}
|
||||
|
||||
/// `memory_id` is the caller's to choose, so a preview run could name a deployed
|
||||
/// conversation and the reverse. A conversation's kind is fixed at creation and nothing
|
||||
/// would show the mixing afterwards, so the turn is refused before it starts.
|
||||
fn same_kind(existing: FlowConversation, is_test: bool) -> Result<FlowConversation> {
|
||||
if existing.is_test == is_test {
|
||||
return Ok(existing);
|
||||
}
|
||||
Err(crate::error::Error::BadRequest(if existing.is_test {
|
||||
"this conversation was started from the flow editor's test panel; start a new conversation to run the deployed flow".to_string()
|
||||
} else {
|
||||
"this conversation belongs to the deployed flow; start a new conversation to test from the flow editor".to_string()
|
||||
}))
|
||||
}
|
||||
|
||||
/// Locked, so a turn orders against retention collecting the conversation
|
||||
@@ -83,7 +128,7 @@ async fn lock_conversation(
|
||||
) -> Result<Option<FlowConversation>> {
|
||||
Ok(sqlx::query_as!(
|
||||
FlowConversation,
|
||||
"SELECT id, workspace_id, flow_path, title, created_at, updated_at, created_by
|
||||
"SELECT id, workspace_id, flow_path, title, created_at, updated_at, created_by, is_test
|
||||
FROM flow_conversation
|
||||
WHERE id = $1 AND workspace_id = $2
|
||||
FOR UPDATE",
|
||||
@@ -164,3 +209,26 @@ pub async fn delete_conversation_memory(
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// A string names a memory only within its workspace and flow; a uuid is used as is.
|
||||
#[test]
|
||||
fn memory_key_scopes_strings_but_not_uuids() {
|
||||
let key = memory_key("ws", "f/support/triage", " customer-1 ");
|
||||
assert_eq!(key, memory_key("ws", "f/support/triage", "customer-1"));
|
||||
assert_ne!(
|
||||
key,
|
||||
memory_key("other_ws", "f/support/triage", "customer-1")
|
||||
);
|
||||
assert_ne!(key, memory_key("ws", "f/sales/triage", "customer-1"));
|
||||
let conversation = Uuid::from_u128(7).to_string();
|
||||
assert_eq!(memory_key("ws", "f/a", &conversation), Uuid::from_u128(7));
|
||||
assert_eq!(
|
||||
memory_key("other_ws", "f/b", &conversation),
|
||||
Uuid::from_u128(7)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -976,18 +976,33 @@ fn six_fields_hint(schedule_str: &str, version: Option<&str>, seconds_required:
|
||||
}
|
||||
|
||||
impl ScheduleType {
|
||||
/// `NotFound` means the expression has no run left (an expired year, an impossible
|
||||
/// date), and schedule pushes disable the schedule on it. Every other error must stay
|
||||
/// transient: croner fails across a DST jump longer than an hour (Antarctica/Troll)
|
||||
/// and succeeds again once the jump has passed.
|
||||
pub fn find_next(
|
||||
&self,
|
||||
starting_from: &chrono::DateTime<chrono_tz::Tz>,
|
||||
) -> chrono::DateTime<chrono_tz::Tz> {
|
||||
) -> Result<chrono::DateTime<chrono_tz::Tz>> {
|
||||
let no_run_left = || {
|
||||
Error::NotFound(format!(
|
||||
"cron: the schedule has no run left after {}",
|
||||
starting_from.format("%Y-%m-%d %H:%M:%S %Z")
|
||||
))
|
||||
};
|
||||
match self {
|
||||
ScheduleType::Croner(croner_schedule) => croner_schedule
|
||||
.find_next_occurrence(starting_from, false)
|
||||
.expect("cron: a schedule should have a next event"),
|
||||
ScheduleType::Cron(schedule) => schedule
|
||||
.after(starting_from)
|
||||
.next()
|
||||
.expect("cron: a schedule should have a next event"),
|
||||
.map_err(|e| match e {
|
||||
croner::errors::CronError::TimeSearchLimitExceeded => no_run_left(),
|
||||
e => Error::internal_err(format!(
|
||||
"cron: could not compute the run after {}: {e}",
|
||||
starting_from.format("%Y-%m-%d %H:%M:%S %Z")
|
||||
)),
|
||||
}),
|
||||
ScheduleType::Cron(schedule) => {
|
||||
schedule.after(starting_from).next().ok_or_else(no_run_left)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1709,6 +1724,22 @@ mod tests {
|
||||
assert!(!err.contains("6 fields"), "{err}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn find_next_reports_only_a_cron_with_no_run_left_as_not_found() {
|
||||
use chrono::TimeZone;
|
||||
let troll: chrono_tz::Tz = "Antarctica/Troll".parse().unwrap();
|
||||
// Troll's clocks jump from 01:00 to 03:00 on the last Sunday of March.
|
||||
let before_jump = troll.with_ymd_and_hms(2027, 3, 28, 0, 30, 0).unwrap();
|
||||
|
||||
let expired = ScheduleType::from_str("0 0 9 1 1 * 2026", Some("v1"), true).unwrap();
|
||||
let err = expired.find_next(&before_jump).unwrap_err();
|
||||
assert!(matches!(err, Error::NotFound(_)), "{err}");
|
||||
|
||||
let across_jump = ScheduleType::from_str("0 30 1 * * *", Some("v2"), true).unwrap();
|
||||
let err = across_jump.find_next(&before_jump).unwrap_err();
|
||||
assert!(!matches!(err, Error::NotFound(_)), "{err}");
|
||||
}
|
||||
|
||||
/// A worker that restarts must land on the exact same name to reclaim its `worker_ping`
|
||||
/// row, while still never colliding with the other workers of its own process. The
|
||||
/// suffix must also stay a single `-` segment, which is what the interactive shell tag
|
||||
|
||||
@@ -166,13 +166,10 @@ pub async fn push_scheduled_job<'c>(
|
||||
}
|
||||
};
|
||||
|
||||
let next = sched.find_next(&starting_from);
|
||||
// println!("next event ({:?}): {}", tz, next);
|
||||
// println!("next event(UTC): {}", next.with_timezone(&chrono::Utc));
|
||||
let next = sched.find_next(&starting_from)?;
|
||||
|
||||
// Scheduled events must be stored in the database in UTC
|
||||
let next = next.with_timezone(&chrono::Utc);
|
||||
// panic!("next: {}", next);
|
||||
let already_exists: bool = sqlx::query_scalar!(
|
||||
// Query plan:
|
||||
// - use of the `ix_v2_job_root_by_path` index; hence the `parent_job IS NULL` clause.
|
||||
|
||||
@@ -921,6 +921,47 @@ mod schedule_push {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// try_schedule_next_job: a cron with no run left disables the schedule
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
#[sqlx::test(migrations = "../migrations", fixtures("base", "schedule_push"))]
|
||||
async fn test_cron_with_no_run_left_disables_schedule(
|
||||
db: Pool<Postgres>,
|
||||
) -> anyhow::Result<()> {
|
||||
sqlx::query(
|
||||
"INSERT INTO schedule (workspace_id, path, edited_by, edited_at, schedule, timezone, enabled, script_path, is_flow, email, extra_perms, ws_error_handler_muted, no_flow_overlap, permissioned_as, cron_version)
|
||||
VALUES ('test-workspace', 'f/system/test_schedule', 'test-user', now(), '0 0 9 1 1 * 2020', 'UTC', true, 'f/system/test_script', false, 'test@windmill.dev', '{}', false, false, 'u/test-user', 'v1')"
|
||||
)
|
||||
.execute(&db)
|
||||
.await?;
|
||||
|
||||
let schedule = make_schedule(|s| {
|
||||
s.schedule = "0 0 9 1 1 * 2020".to_string();
|
||||
s.cron_version = Some("v1".to_string());
|
||||
});
|
||||
let job = make_completed_job(&schedule);
|
||||
|
||||
let tx = db.begin().await?;
|
||||
let (tx, err) =
|
||||
try_schedule_next_job(&db, tx, &job, &schedule, &schedule.script_path).await;
|
||||
assert!(err.is_none(), "completion must go through, got: {err:?}");
|
||||
tx.commit().await?;
|
||||
|
||||
assert_eq!(count_queued_jobs(&db).await, 0);
|
||||
let (enabled, error): (bool, Option<String>) = sqlx::query_as(
|
||||
"SELECT enabled, error FROM schedule WHERE workspace_id = 'test-workspace' AND path = 'f/system/test_schedule'",
|
||||
)
|
||||
.fetch_one(&db)
|
||||
.await?;
|
||||
assert!(!enabled, "schedule with no run left must be disabled");
|
||||
assert!(
|
||||
error.as_deref().is_some_and(|e| e.contains("no run left")),
|
||||
"error should say why, got: {error:?}"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// try_schedule_next_job: disabled schedule leaves no side effects
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
@@ -1100,7 +1100,8 @@ pub enum FlowModuleValue {
|
||||
omit_output_from_conversation: bool,
|
||||
/// When set, the agent brain config (provider/model/system prompt/etc.) and tools are
|
||||
/// resolved at runtime from this `ai_agent` resource path (hybrid linking). The module's
|
||||
/// `input_transforms` then only carry the flow-local inputs (user_message/user_attachments).
|
||||
/// `input_transforms` then only carry the flow-local inputs: user_message,
|
||||
/// user_attachments, enabled_tools and the history inputs memory_id and previous_messages.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
agent: Option<String>,
|
||||
/// Binds an agent's tools to *this* flow's context, keyed by tool id then input key, without
|
||||
|
||||
@@ -154,6 +154,8 @@ pub async fn get_flow_job_runnable_and_raw_flow(
|
||||
pub struct FlowContext {
|
||||
pub flow_inputs: Option<HashMap<String, Box<RawValue>>>,
|
||||
pub flow_status: Option<windmill_common::flow_status::FlowStatus>,
|
||||
/// Path of the flow the run started from, which scopes a string memory id.
|
||||
pub flow_path: Option<String>,
|
||||
}
|
||||
|
||||
/// Get flow context (chat settings + args + flow_status) from root flow's job data
|
||||
@@ -171,7 +173,8 @@ pub async fn get_flow_context(db: &DB, job: &MiniPulledJob) -> FlowContext {
|
||||
r#"
|
||||
SELECT
|
||||
j.args as "args: Json<HashMap<String, Box<RawValue>>>",
|
||||
js.flow_status as "flow_status: Json<windmill_common::flow_status::FlowStatus>"
|
||||
js.flow_status as "flow_status: Json<windmill_common::flow_status::FlowStatus>",
|
||||
j.runnable_path
|
||||
FROM v2_job_status js
|
||||
INNER JOIN v2_job j ON j.id = js.id
|
||||
WHERE js.id = $1
|
||||
@@ -184,6 +187,7 @@ pub async fn get_flow_context(db: &DB, job: &MiniPulledJob) -> FlowContext {
|
||||
Ok(Some(row)) => FlowContext {
|
||||
flow_inputs: row.args.map(|j| j.0),
|
||||
flow_status: row.flow_status.map(|j| j.0),
|
||||
flow_path: row.runnable_path,
|
||||
},
|
||||
Ok(None) => {
|
||||
tracing::warn!(
|
||||
|
||||
@@ -44,7 +44,7 @@ use windmill_common::{
|
||||
client::AuthedClient,
|
||||
db::DB,
|
||||
error::{self, Error},
|
||||
flow_conversations::MessageType,
|
||||
flow_conversations::{memory_key, MessageType},
|
||||
flow_status::AgentAction,
|
||||
flows::{AgentTool, FlowModule, FlowModuleValue, InputTransform, ToolValue},
|
||||
get_latest_hash_for_path,
|
||||
@@ -111,6 +111,148 @@ fn prepare_auto_memory_messages_for_persistence(
|
||||
non_system_messages[start_idx..].to_vec()
|
||||
}
|
||||
|
||||
/// The inputs a linked step supplies for itself; the resource holds the rest of the brain.
|
||||
const FLOW_LOCAL_AGENT_KEYS: [&str; 5] = [
|
||||
"user_message",
|
||||
"user_attachments",
|
||||
"enabled_tools",
|
||||
"memory_id",
|
||||
"previous_messages",
|
||||
];
|
||||
|
||||
/// The flow-local inputs that name a conversation, which a saved agent never carries.
|
||||
const STEP_HISTORY_KEYS: [&str; 2] = ["memory_id", "previous_messages"];
|
||||
|
||||
/// Where one agent invocation's history comes from.
|
||||
#[derive(Debug)]
|
||||
enum HistorySource<'a> {
|
||||
/// Supplied by the flow and replayed as is: memory is neither read nor written.
|
||||
Messages(&'a [OpenAIMessage]),
|
||||
Window {
|
||||
memory_id: Uuid,
|
||||
context_length: usize,
|
||||
},
|
||||
Stateless,
|
||||
}
|
||||
|
||||
/// A step's memory id counts only as the step authored it. A static empty value is a form
|
||||
/// placeholder, so it reads as unset rather than as an expression that evaluated to nothing, which
|
||||
/// runs without memory; an AI-filled value would let the model choose which memory the agent reads.
|
||||
fn keep_authored_memory_id(
|
||||
args: &mut AIAgentArgs,
|
||||
step_input_transforms: &HashMap<String, InputTransform>,
|
||||
) {
|
||||
match step_input_transforms.get("memory_id") {
|
||||
Some(InputTransform::Javascript { .. }) => {}
|
||||
Some(InputTransform::Static { .. }) if args.memory_id.as_deref() != Some("") => {}
|
||||
_ => args.memory_id = None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Reconciles the step's history inputs, the agent's memory policy and the run's memory id. A step
|
||||
/// holds one of two shapes: an older `auto` or `manual` memory, read as the editor that wrote it
|
||||
/// meant it, or the current setting plus the step's own history inputs. Also returns lines for the
|
||||
/// job log: an input that went unused, or a policy that remembers ending up stateless.
|
||||
fn resolve_history_source<'a>(
|
||||
args: &'a AIAgentArgs,
|
||||
run_memory_id: Option<Uuid>,
|
||||
workspace_id: &str,
|
||||
flow_path: &str,
|
||||
) -> (HistorySource<'a>, Vec<&'static str>) {
|
||||
let mut notes = Vec::new();
|
||||
let no_memory_id = "No memory id was passed to this run, so the agent runs without memory.";
|
||||
match &args.memory {
|
||||
// The step's own history inputs came after these, so a step that still holds one reads it
|
||||
// alone: what it did before the editor offered them is what it keeps doing.
|
||||
Some(Memory::Manual { messages }) => {
|
||||
note_unread_step_inputs(&mut notes, args);
|
||||
(HistorySource::Messages(messages), notes)
|
||||
}
|
||||
Some(Memory::Auto { context_length, memory_id }) => {
|
||||
note_unread_step_inputs(&mut notes, args);
|
||||
// An id baked in at save time only ever applied when the run carried none.
|
||||
match run_memory_id.or(*memory_id) {
|
||||
Some(memory_id) => (
|
||||
HistorySource::Window { memory_id, context_length: *context_length },
|
||||
notes,
|
||||
),
|
||||
None => {
|
||||
notes.push(no_memory_id);
|
||||
(HistorySource::Stateless, notes)
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(Memory::Window { context_length }) => {
|
||||
if args
|
||||
.previous_messages
|
||||
.as_ref()
|
||||
.is_some_and(|messages| !messages.is_empty())
|
||||
{
|
||||
notes.push("Managed memory is on, so this step's previous messages are ignored.");
|
||||
}
|
||||
let memory_id = match args.memory_id.as_deref() {
|
||||
Some("") => {
|
||||
notes.push(
|
||||
"This step's memory id evaluated to an empty value, so the agent runs without memory.",
|
||||
);
|
||||
return (HistorySource::Stateless, notes);
|
||||
}
|
||||
Some(step_memory_id) => memory_key(workspace_id, flow_path, step_memory_id),
|
||||
None => match run_memory_id {
|
||||
Some(memory_id) => memory_id,
|
||||
None => {
|
||||
notes.push(no_memory_id);
|
||||
return (HistorySource::Stateless, notes);
|
||||
}
|
||||
},
|
||||
};
|
||||
(
|
||||
HistorySource::Window { memory_id, context_length: *context_length },
|
||||
notes,
|
||||
)
|
||||
}
|
||||
Some(Memory::Off) | None => {
|
||||
if args.memory_id.as_deref().is_some_and(|id| !id.is_empty()) {
|
||||
notes.push("Managed memory is off, so this step's memory id is ignored.");
|
||||
}
|
||||
match &args.previous_messages {
|
||||
Some(messages) => (HistorySource::Messages(messages), notes),
|
||||
None => (HistorySource::Stateless, notes),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An older memory setting reads neither history input, which is only visible in the job log: the
|
||||
/// editor offers them on a step that has been moved to the current settings.
|
||||
fn note_unread_step_inputs(notes: &mut Vec<&'static str>, args: &AIAgentArgs) {
|
||||
if args.memory_id.as_deref().is_some_and(|id| !id.is_empty()) {
|
||||
notes.push("This step uses an older memory setting, so its memory id is not read.");
|
||||
}
|
||||
if args
|
||||
.previous_messages
|
||||
.as_ref()
|
||||
.is_some_and(|messages| !messages.is_empty())
|
||||
{
|
||||
notes
|
||||
.push("This step uses an older memory setting, so its previous messages are not read.");
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a request has something to ask the model. Only text output sends previous messages, so
|
||||
/// an image prompt comes from the user message alone. An empty list is no conversation, except
|
||||
/// under a legacy `manual` memory, which ran on whatever list it held.
|
||||
fn has_prompt(
|
||||
history: &HistorySource,
|
||||
has_user_message: bool,
|
||||
is_text_output: bool,
|
||||
legacy_list: bool,
|
||||
) -> bool {
|
||||
has_user_message
|
||||
|| (is_text_output
|
||||
&& (legacy_list || matches!(history, HistorySource::Messages(m) if !m.is_empty())))
|
||||
}
|
||||
|
||||
fn find_module_by_id(
|
||||
modules: &Vec<FlowModule>,
|
||||
target_id: &str,
|
||||
@@ -136,14 +278,16 @@ async fn find_ai_agent_tool_module_in_parent_agent(
|
||||
return Ok(None);
|
||||
};
|
||||
|
||||
let FlowModuleValue::AIAgent { tools, agent, .. } = parent_agent_module.get_value()? else {
|
||||
let FlowModuleValue::AIAgent { tools, agent, tool_inputs, .. } =
|
||||
parent_agent_module.get_value()?
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
|
||||
// A linked parent carries no tools on the module (they live in the resource, resolved only in
|
||||
// the main execution branch). Resolve them from the resource here too, so a nested agent tool
|
||||
// of a saved+linked agent can still be located when it runs as its own job.
|
||||
let tools = if let Some(agent_ref) = agent.as_deref() {
|
||||
let mut tools = if let Some(agent_ref) = agent.as_deref() {
|
||||
let agent_path = agent_ref
|
||||
.trim_start_matches("$res:")
|
||||
.trim_start_matches("res://");
|
||||
@@ -170,6 +314,9 @@ async fn find_ai_agent_tool_module_in_parent_agent(
|
||||
} else {
|
||||
tools
|
||||
};
|
||||
// The nested job reads its history inputs from the tool's transforms, which must carry the
|
||||
// host flow's bindings as the parent evaluated them.
|
||||
overlay_tool_inputs(&mut tools, &tool_inputs);
|
||||
|
||||
for tool in tools {
|
||||
if tool.id == tool_module_id {
|
||||
@@ -456,6 +603,7 @@ pub async fn handle_ai_agent_job(
|
||||
omit_output_from_conversation,
|
||||
agent,
|
||||
tool_inputs,
|
||||
input_transforms: step_input_transforms,
|
||||
..
|
||||
} = module.get_value()?
|
||||
else {
|
||||
@@ -466,9 +614,11 @@ pub async fn handle_ai_agent_job(
|
||||
|
||||
// A linked step takes its brain and tools from the resource and keeps only its own flow-local
|
||||
// inputs. The brain and the roster stay rigid; what the step binds to this flow is the message
|
||||
// it asks, which of those tools this use may call, the conversation it is part of, and the
|
||||
// tools' own inputs — the last overlaid from `tool_inputs` below.
|
||||
let (args, tools): (AIAgentArgs, Vec<AgentTool>) = if let Some(agent_ref) = agent.as_deref() {
|
||||
// it asks, which of those tools this use may call, the conversation it is part of (its memory
|
||||
// id and previous messages), and the tools' own inputs — the last overlaid from `tool_inputs`
|
||||
// below.
|
||||
let (mut args, tools): (AIAgentArgs, Vec<AgentTool>) = if let Some(agent_ref) = agent.as_deref()
|
||||
{
|
||||
let agent_path = agent_ref
|
||||
.trim_start_matches("$res:")
|
||||
.trim_start_matches("res://");
|
||||
@@ -500,6 +650,12 @@ pub async fn handle_ai_agent_job(
|
||||
None => Vec::new(),
|
||||
};
|
||||
overlay_tool_inputs(&mut tools, &tool_inputs);
|
||||
// The resource is not validated against a schema, so a history input it happens to carry
|
||||
// is dropped before interpolation, where a bad `$res:` in it would fail the step. The
|
||||
// other flow-local keys stay: a resource's own user message is the step's fallback.
|
||||
for key in STEP_HISTORY_KEYS {
|
||||
config.remove(key);
|
||||
}
|
||||
let brain = transform_json_value(
|
||||
"ai_agent",
|
||||
client,
|
||||
@@ -521,7 +677,7 @@ pub async fn handle_ai_agent_job(
|
||||
// Only after interpolating the resource: these are caller-controlled and already resolved by
|
||||
// build_args_map, so passing them through it again would expand contextual values —
|
||||
// `$WM_TOKEN` in a user message would reach the model provider.
|
||||
for key in ["user_message", "user_attachments", "enabled_tools"] {
|
||||
for key in FLOW_LOCAL_AGENT_KEYS {
|
||||
if let Some(v) = local_args.get(key) {
|
||||
brain.insert(
|
||||
key.to_string(),
|
||||
@@ -546,6 +702,8 @@ pub async fn handle_ai_agent_job(
|
||||
(args, tools)
|
||||
};
|
||||
|
||||
keep_authored_memory_id(&mut args, &step_input_transforms);
|
||||
|
||||
// Nesting is capped at flow → agent → nested agent. When this job is itself a nested tool,
|
||||
// a linked resource's tool set may still contain AIAgent tools (the editor can't constrain a
|
||||
// shared resource); don't advertise them — invoking one would only fail the depth check as a
|
||||
@@ -1010,8 +1168,18 @@ pub async fn run_agent(
|
||||
// Fetch flow context for input transforms context, chat and memory
|
||||
let mut flow_context = get_flow_context(db, job).await;
|
||||
|
||||
// Determine if we're using manual messages (which bypasses memory)
|
||||
let use_manual_messages = matches!(args.memory, Some(Memory::Manual { .. }));
|
||||
// The run's memory id is also the chat conversation id, which a step's own memory id never
|
||||
// replaces.
|
||||
let conversation_id = flow_context
|
||||
.flow_status
|
||||
.as_ref()
|
||||
.and_then(|fs| fs.memory_id);
|
||||
let (history, history_notes) = resolve_history_source(
|
||||
args,
|
||||
conversation_id,
|
||||
&job.workspace_id,
|
||||
flow_context.flow_path.as_deref().unwrap_or_default(),
|
||||
);
|
||||
|
||||
// Check if user_message is provided and non-empty
|
||||
let has_user_message = args
|
||||
@@ -1020,63 +1188,63 @@ pub async fn run_agent(
|
||||
.map(|m| !m.is_empty())
|
||||
.unwrap_or(false);
|
||||
|
||||
// Validate: at least one of memory with manual messages or user_message must be provided
|
||||
if !use_manual_messages && !has_user_message {
|
||||
return Err(Error::internal_err(
|
||||
"Either 'memory' with manual messages or 'user_message' must be provided".to_string(),
|
||||
));
|
||||
}
|
||||
|
||||
let is_text_output = output_type == &OutputType::Text;
|
||||
|
||||
// Flow-level memory_id (from chat mode) takes precedence over step-level memory_id
|
||||
let memory_id = flow_context
|
||||
.flow_status
|
||||
.as_ref()
|
||||
.and_then(|fs| fs.memory_id)
|
||||
.or_else(|| {
|
||||
// Extract memory_id from Memory::Auto if present
|
||||
match &args.memory {
|
||||
Some(Memory::Auto { memory_id, .. }) => *memory_id,
|
||||
_ => None,
|
||||
}
|
||||
});
|
||||
if is_text_output {
|
||||
for note in &history_notes {
|
||||
append_logs(&job.id, &job.workspace_id, format!("{note}\n"), conn).await;
|
||||
}
|
||||
} else if !matches!(args.memory, None | Some(Memory::Off))
|
||||
|| args.memory_id.is_some()
|
||||
|| args.previous_messages.is_some()
|
||||
{
|
||||
append_logs(
|
||||
&job.id,
|
||||
&job.workspace_id,
|
||||
"Image output sends no history, so memory and previous messages are not read.\n",
|
||||
conn,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
// A `manual` memory sent whatever list it held, an empty one included, so a step that still has
|
||||
// one keeps running without a user message.
|
||||
let legacy_list = matches!(args.memory, Some(Memory::Manual { .. }));
|
||||
if !has_prompt(&history, has_user_message, is_text_output, legacy_list) {
|
||||
let missing = if !is_text_output {
|
||||
"'user_message' must be provided for image output"
|
||||
} else if matches!(
|
||||
args.memory,
|
||||
Some(Memory::Window { .. } | Memory::Auto { .. })
|
||||
) {
|
||||
"'user_message' must be provided while managed memory is on"
|
||||
} else {
|
||||
"Either 'previous_messages' or 'user_message' must be provided"
|
||||
};
|
||||
return Err(Error::internal_err(missing.to_string()));
|
||||
}
|
||||
|
||||
// Load messages based on history mode
|
||||
if matches!(output_type, OutputType::Text) {
|
||||
match &args.memory {
|
||||
Some(Memory::Manual { messages: manual_messages }) => {
|
||||
// Use explicitly provided messages (bypass memory)
|
||||
if !manual_messages.is_empty() {
|
||||
messages.extend(manual_messages.clone());
|
||||
}
|
||||
}
|
||||
Some(Memory::Auto { context_length, .. }) => {
|
||||
// Auto mode: load from memory
|
||||
match &history {
|
||||
HistorySource::Messages(provided) => messages.extend(provided.iter().cloned()),
|
||||
HistorySource::Window { memory_id, context_length } => {
|
||||
if let Some(step_id) = effective_flow_step_id {
|
||||
if let Some(memory_id) = memory_id {
|
||||
// Read messages from memory
|
||||
match read_from_memory(db, &job.workspace_id, memory_id, step_id).await {
|
||||
Ok(Some(loaded_messages)) => {
|
||||
let messages_to_load = prepare_auto_memory_messages_for_request(
|
||||
&loaded_messages,
|
||||
*context_length,
|
||||
);
|
||||
messages.extend(messages_to_load);
|
||||
}
|
||||
Ok(None) => {}
|
||||
Err(e) => {
|
||||
tracing::error!(
|
||||
"Failed to read memory for step {}: {}",
|
||||
step_id,
|
||||
e
|
||||
);
|
||||
}
|
||||
match read_from_memory(db, &job.workspace_id, *memory_id, step_id).await {
|
||||
Ok(Some(loaded_messages)) => {
|
||||
let messages_to_load = prepare_auto_memory_messages_for_request(
|
||||
&loaded_messages,
|
||||
*context_length,
|
||||
);
|
||||
messages.extend(messages_to_load);
|
||||
}
|
||||
Ok(None) => {}
|
||||
Err(e) => {
|
||||
tracing::error!("Failed to read memory for step {}: {}", step_id, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
HistorySource::Stateless => {}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1521,7 +1689,7 @@ pub async fn run_agent(
|
||||
..Default::default()
|
||||
});
|
||||
if persist_output_to_conversation {
|
||||
if let Some(memory_id) = memory_id {
|
||||
if let Some(conversation_id) = conversation_id {
|
||||
let agent_job_id = job.id;
|
||||
let db_clone = db.clone();
|
||||
let message_content = "Used websearch tool successfully".to_string();
|
||||
@@ -1529,7 +1697,7 @@ pub async fn run_agent(
|
||||
tokio::spawn(async move {
|
||||
if let Err(e) = add_message_to_conversation(
|
||||
&db_clone,
|
||||
&memory_id,
|
||||
&conversation_id,
|
||||
Some(agent_job_id),
|
||||
&message_content,
|
||||
MessageType::Tool,
|
||||
@@ -1540,7 +1708,7 @@ pub async fn run_agent(
|
||||
{
|
||||
tracing::warn!(
|
||||
"Failed to add websearch tool message to conversation {}: {}",
|
||||
memory_id,
|
||||
conversation_id,
|
||||
e
|
||||
);
|
||||
}
|
||||
@@ -1573,7 +1741,7 @@ pub async fn run_agent(
|
||||
|
||||
// Add assistant message to conversation if chat_input_enabled
|
||||
if persist_output_to_conversation && !response_content.is_empty() {
|
||||
if let Some(memory_id) = memory_id {
|
||||
if let Some(conversation_id) = conversation_id {
|
||||
let agent_job_id = job.id;
|
||||
let db_clone = db.clone();
|
||||
let message_content = response_content.clone();
|
||||
@@ -1583,7 +1751,7 @@ pub async fn run_agent(
|
||||
tokio::spawn(async move {
|
||||
if let Err(e) = add_message_to_conversation(
|
||||
&db_clone,
|
||||
&memory_id,
|
||||
&conversation_id,
|
||||
Some(agent_job_id),
|
||||
&message_content,
|
||||
MessageType::Assistant,
|
||||
@@ -1594,7 +1762,7 @@ pub async fn run_agent(
|
||||
{
|
||||
tracing::warn!(
|
||||
"Failed to add assistant message to conversation {}: {}",
|
||||
memory_id,
|
||||
conversation_id,
|
||||
e
|
||||
);
|
||||
}
|
||||
@@ -1692,7 +1860,7 @@ pub async fn run_agent(
|
||||
|
||||
// Add assistant message to conversation if chat_input_enabled
|
||||
if persist_output_to_conversation {
|
||||
if let Some(memory_id) = memory_id {
|
||||
if let Some(conversation_id) = conversation_id {
|
||||
let agent_job_id = job.id;
|
||||
let db_clone = db.clone();
|
||||
|
||||
@@ -1710,7 +1878,7 @@ pub async fn run_agent(
|
||||
tokio::spawn(async move {
|
||||
if let Err(e) = add_message_to_conversation(
|
||||
&db_clone,
|
||||
&memory_id,
|
||||
&conversation_id,
|
||||
Some(agent_job_id),
|
||||
&message_content,
|
||||
MessageType::Assistant,
|
||||
@@ -1721,7 +1889,7 @@ pub async fn run_agent(
|
||||
{
|
||||
tracing::warn!(
|
||||
"Failed to add assistant message to conversation {}: {}",
|
||||
memory_id,
|
||||
conversation_id,
|
||||
e
|
||||
);
|
||||
}
|
||||
@@ -1778,13 +1946,10 @@ pub async fn run_agent(
|
||||
}
|
||||
}
|
||||
|
||||
// Persist complete conversation to memory at the end (only if in auto mode with context length)
|
||||
// Skip memory persistence if using manual messages (bypass memory entirely)
|
||||
// final_messages contains the complete history (old messages + new ones)
|
||||
if matches!(output_type, OutputType::Text) && !use_manual_messages {
|
||||
if let Some(Memory::Auto { context_length, .. }) = &args.memory {
|
||||
// final_messages holds the complete history: what was loaded plus this run's messages
|
||||
if matches!(output_type, OutputType::Text) {
|
||||
if let HistorySource::Window { memory_id, context_length } = &history {
|
||||
if let Some(step_id) = effective_flow_step_id {
|
||||
// Extract OpenAIMessages from final_messages
|
||||
let all_messages: Vec<OpenAIMessage> =
|
||||
final_messages.iter().map(|m| m.message.clone()).collect();
|
||||
|
||||
@@ -1794,23 +1959,21 @@ pub async fn run_agent(
|
||||
*context_length,
|
||||
);
|
||||
|
||||
if let Some(memory_id) = memory_id {
|
||||
if let Err(e) = write_to_memory(
|
||||
db,
|
||||
&job.workspace_id,
|
||||
memory_id,
|
||||
if let Err(e) = write_to_memory(
|
||||
db,
|
||||
&job.workspace_id,
|
||||
*memory_id,
|
||||
step_id,
|
||||
&messages_to_persist,
|
||||
)
|
||||
.await
|
||||
{
|
||||
tracing::error!(
|
||||
"Failed to persist {} messages to memory for step {}: {}",
|
||||
messages_to_persist.len(),
|
||||
step_id,
|
||||
&messages_to_persist,
|
||||
)
|
||||
.await
|
||||
{
|
||||
tracing::error!(
|
||||
"Failed to persist {} messages to memory for step {}: {}",
|
||||
messages_to_persist.len(),
|
||||
step_id,
|
||||
e
|
||||
);
|
||||
}
|
||||
e
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1870,6 +2033,228 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq)]
|
||||
enum Resolved {
|
||||
Messages(usize),
|
||||
Window(Uuid, usize),
|
||||
Stateless { noted: bool },
|
||||
}
|
||||
|
||||
/// Every memory shape a worker may still read, resolved against a run with or without a
|
||||
/// memory id. The hashed id is pinned: changing it detaches memories stored under string ids.
|
||||
#[test]
|
||||
fn history_source_resolves_every_memory_shape() {
|
||||
use serde_json::json;
|
||||
let run = Uuid::from_u128(1);
|
||||
let baked = Uuid::from_u128(2);
|
||||
let cust_1 = Uuid::parse_str("0168fcea-ffa7-5c15-bdb0-7709bb5f540d").unwrap();
|
||||
let window = json!({ "kind": "window", "context_length": 10 });
|
||||
let message = json!([{ "role": "user", "content": "earlier" }]);
|
||||
let two_messages = json!([
|
||||
{ "role": "user", "content": "earlier" },
|
||||
{ "role": "assistant", "content": "reply" }
|
||||
]);
|
||||
let cases = [
|
||||
(
|
||||
"absent memory is off",
|
||||
json!({}),
|
||||
Some(run),
|
||||
Resolved::Stateless { noted: false },
|
||||
),
|
||||
(
|
||||
"legacy off",
|
||||
json!({ "memory": { "kind": "off" } }),
|
||||
Some(run),
|
||||
Resolved::Stateless { noted: false },
|
||||
),
|
||||
(
|
||||
"legacy auto prefers the run's id",
|
||||
json!({ "memory": { "kind": "auto", "context_length": 4, "memory_id": baked } }),
|
||||
Some(run),
|
||||
Resolved::Window(run, 4),
|
||||
),
|
||||
(
|
||||
"legacy auto falls back to its baked id",
|
||||
json!({ "memory": { "kind": "auto", "context_length": 4, "memory_id": baked } }),
|
||||
None,
|
||||
Resolved::Window(baked, 4),
|
||||
),
|
||||
(
|
||||
"legacy auto with an empty baked id uses the run's",
|
||||
json!({ "memory": { "kind": "auto", "context_length": 4, "memory_id": "" } }),
|
||||
Some(run),
|
||||
Resolved::Window(run, 4),
|
||||
),
|
||||
(
|
||||
"legacy auto with an empty baked id and no run id is stateless",
|
||||
json!({ "memory": { "kind": "auto", "context_length": 4, "memory_id": " " } }),
|
||||
None,
|
||||
Resolved::Stateless { noted: true },
|
||||
),
|
||||
(
|
||||
"legacy auto without a length is off",
|
||||
json!({ "memory": { "kind": "auto", "memory_id": baked } }),
|
||||
Some(run),
|
||||
Resolved::Stateless { noted: false },
|
||||
),
|
||||
(
|
||||
"a cleared count is off",
|
||||
json!({ "memory": { "kind": "window", "context_length": null } }),
|
||||
Some(run),
|
||||
Resolved::Stateless { noted: false },
|
||||
),
|
||||
(
|
||||
"legacy manual replays its messages",
|
||||
json!({ "memory": { "kind": "manual", "messages": message } }),
|
||||
Some(run),
|
||||
Resolved::Messages(1),
|
||||
),
|
||||
(
|
||||
"window keeps the run's memory",
|
||||
json!({ "memory": window }),
|
||||
Some(run),
|
||||
Resolved::Window(run, 10),
|
||||
),
|
||||
(
|
||||
"window without a memory id is stateless",
|
||||
json!({ "memory": window }),
|
||||
None,
|
||||
Resolved::Stateless { noted: true },
|
||||
),
|
||||
(
|
||||
"a step memory id overrides the run's",
|
||||
json!({ "memory": window, "memory_id": "cust_1" }),
|
||||
Some(run),
|
||||
Resolved::Window(cust_1, 10),
|
||||
),
|
||||
(
|
||||
"a uuid step memory id is used as is",
|
||||
json!({ "memory": window, "memory_id": baked.to_string() }),
|
||||
Some(run),
|
||||
Resolved::Window(baked, 10),
|
||||
),
|
||||
(
|
||||
"a step memory id evaluating to null is stateless",
|
||||
json!({ "memory": window, "memory_id": null }),
|
||||
Some(run),
|
||||
Resolved::Stateless { noted: true },
|
||||
),
|
||||
(
|
||||
"an off policy ignores the step memory id, and says so",
|
||||
json!({ "memory": { "kind": "off" }, "memory_id": "cust_1" }),
|
||||
Some(run),
|
||||
Resolved::Stateless { noted: true },
|
||||
),
|
||||
(
|
||||
"managed memory ignores the step's previous messages",
|
||||
json!({ "memory": window, "memory_id": "cust_1", "previous_messages": message }),
|
||||
Some(run),
|
||||
Resolved::Window(cust_1, 10),
|
||||
),
|
||||
(
|
||||
"memory that is off sends the step's previous messages",
|
||||
json!({ "previous_messages": message }),
|
||||
Some(run),
|
||||
Resolved::Messages(1),
|
||||
),
|
||||
(
|
||||
"a previous messages expression that evaluated to null is no history",
|
||||
json!({ "previous_messages": null }),
|
||||
Some(run),
|
||||
Resolved::Stateless { noted: false },
|
||||
),
|
||||
(
|
||||
"a legacy manual list ignores the step's previous messages",
|
||||
json!({ "memory": { "kind": "manual", "messages": message }, "previous_messages": two_messages }),
|
||||
Some(run),
|
||||
Resolved::Messages(1),
|
||||
),
|
||||
(
|
||||
"legacy auto ignores a step memory id",
|
||||
json!({ "memory": { "kind": "auto", "context_length": 4, "memory_id": baked }, "memory_id": "cust_1" }),
|
||||
None,
|
||||
Resolved::Window(baked, 4),
|
||||
),
|
||||
];
|
||||
for (name, history, run_memory_id, expected) in cases {
|
||||
let mut raw = json!({ "provider": { "kind": "openai", "resource": {}, "model": "m" } });
|
||||
raw.as_object_mut()
|
||||
.unwrap()
|
||||
.extend(history.as_object().unwrap().clone());
|
||||
let args: AIAgentArgs = serde_json::from_value(raw).unwrap();
|
||||
let resolved = match resolve_history_source(&args, run_memory_id, "ws", "f/flow") {
|
||||
(HistorySource::Messages(m), _) => Resolved::Messages(m.len()),
|
||||
(HistorySource::Window { memory_id, context_length }, _) => {
|
||||
Resolved::Window(memory_id, context_length)
|
||||
}
|
||||
(HistorySource::Stateless, notes) => {
|
||||
Resolved::Stateless { noted: !notes.is_empty() }
|
||||
}
|
||||
};
|
||||
assert_eq!(resolved, expected, "{name}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A placeholder the form seeds must not read as a memory id that evaluated to nothing, which
|
||||
/// would turn memory off for the step.
|
||||
#[test]
|
||||
fn only_an_expression_can_set_an_empty_step_memory_id() {
|
||||
let transforms = |memory_id: &str| -> HashMap<String, InputTransform> {
|
||||
HashMap::from([(
|
||||
"memory_id".to_string(),
|
||||
serde_json::from_str(memory_id).unwrap(),
|
||||
)])
|
||||
};
|
||||
let args = || -> AIAgentArgs {
|
||||
serde_json::from_value(serde_json::json!({
|
||||
"provider": { "kind": "openai", "resource": {}, "model": "m" },
|
||||
"memory_id": null,
|
||||
}))
|
||||
.unwrap()
|
||||
};
|
||||
for (transform, expected) in [
|
||||
(r#"{ "type": "static" }"#, None),
|
||||
(r#"{ "type": "static", "value": "" }"#, None),
|
||||
(r#"{ "type": "ai" }"#, None),
|
||||
(
|
||||
r#"{ "type": "javascript", "expr": "flow_input.customer_id" }"#,
|
||||
Some(""),
|
||||
),
|
||||
] {
|
||||
let mut args = args();
|
||||
keep_authored_memory_id(&mut args, &transforms(transform));
|
||||
assert_eq!(args.memory_id.as_deref(), expected, "{transform}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Only text output sends previous messages, so they never stand in for an image prompt.
|
||||
#[test]
|
||||
fn previous_messages_never_stand_in_for_an_image_prompt() {
|
||||
let args: AIAgentArgs = serde_json::from_value(serde_json::json!({
|
||||
"provider": { "kind": "openai", "resource": {}, "model": "m" },
|
||||
"previous_messages": [{ "role": "user", "content": "earlier" }],
|
||||
}))
|
||||
.unwrap();
|
||||
let (history, _) = resolve_history_source(&args, None, "ws", "f/flow");
|
||||
assert!(has_prompt(&history, false, true, false));
|
||||
assert!(!has_prompt(&history, false, false, false));
|
||||
assert!(has_prompt(&history, true, false, false));
|
||||
assert!(!has_prompt(
|
||||
&HistorySource::Messages(&[]),
|
||||
false,
|
||||
true,
|
||||
false
|
||||
));
|
||||
// A legacy `manual` memory ran on an empty list alone, and still does for text output.
|
||||
assert!(has_prompt(&HistorySource::Messages(&[]), false, true, true));
|
||||
assert!(!has_prompt(
|
||||
&HistorySource::Messages(&[]),
|
||||
false,
|
||||
false,
|
||||
true
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reasoning_keeps_every_iteration_in_order() {
|
||||
let mut acc = String::new();
|
||||
|
||||
+5
-2
@@ -225,8 +225,11 @@ answer, an `assistant` message with `success: false`. `status: 'error'` (with `e
|
||||
set) means the turn could not run or be followed at all, such as a refused request.
|
||||
|
||||
Methods: `sendMessage(text, { inputs? })`, `stop()`, `newConversation()`,
|
||||
`selectConversation(id)`, `loadConversations({ page?, perPage? })`,
|
||||
`deleteConversation(id)`, `loadOlderMessages()`, `destroy()`. Switching conversations
|
||||
`selectConversation(id)`, `loadConversations({ page?, perPage?, kind? })`,
|
||||
`deleteConversation(id)`, `renameConversation(id, title)`, `loadOlderMessages()`,
|
||||
`destroy()`. `kind` lists the flow editor's test chats (`'test'`), the deployed flow's
|
||||
own (`'deployed'`, the server's default) or both (`'all'`); each `Conversation` carries
|
||||
`isTest`. A rename keeps the conversation's place in the list. Switching conversations
|
||||
stops following the current answer; the flow keeps running and, with server history,
|
||||
its answer is there when you come back.
|
||||
|
||||
|
||||
+20
-2
@@ -28,8 +28,16 @@ export interface FlowConversation {
|
||||
created_at: string
|
||||
updated_at: string
|
||||
created_by: string
|
||||
/** Started from the flow editor's test panel rather than a deployed run. */
|
||||
is_test: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* Which conversations a listing holds: the flow editor's test chats, the deployed flow's
|
||||
* own (the server's default), or both.
|
||||
*/
|
||||
export type ConversationKind = 'test' | 'deployed' | 'all'
|
||||
|
||||
export interface FlowConversationMessage {
|
||||
id: string
|
||||
conversation_id: string
|
||||
@@ -167,15 +175,25 @@ export class WindmillChatApi {
|
||||
|
||||
async listConversations(
|
||||
flowPath: string,
|
||||
options: { page?: number; perPage?: number; signal?: AbortSignal } = {}
|
||||
options: { page?: number; perPage?: number; kind?: ConversationKind; signal?: AbortSignal } = {}
|
||||
): Promise<FlowConversation[]> {
|
||||
const extra: Record<string, string> = { flow_path: flowPath }
|
||||
if (options.kind !== undefined) extra.kind = options.kind
|
||||
const res = await this.#request('flow_conversations/list', {
|
||||
query: pagination(options, { flow_path: flowPath }),
|
||||
query: pagination(options, extra),
|
||||
signal: options.signal
|
||||
})
|
||||
return (await res.json()) as FlowConversation[]
|
||||
}
|
||||
|
||||
/** Sets a conversation's title. Its place in the list is kept: only a turn moves one. */
|
||||
async renameConversation(conversationId: string, title: string): Promise<void> {
|
||||
await this.#request(`flow_conversations/update/${encodeURIComponent(conversationId)}`, {
|
||||
method: 'POST',
|
||||
body: { title }
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Without `afterSeq`: one page counted from the newest message, returned oldest first.
|
||||
* With `afterSeq`: the messages created after that cursor, oldest first.
|
||||
|
||||
@@ -53,7 +53,8 @@ export function useWindmillRuntime(options: WindmillRuntimeOptions): AssistantRu
|
||||
threads: chat.conversations.map((c) => ({ status: 'regular' as const, id: c.id, title: c.title })),
|
||||
onSwitchToNewThread: () => chat.newConversation(),
|
||||
onSwitchToThread: (id) => chat.selectConversation(id),
|
||||
onDelete: (id) => chat.deleteConversation(id)
|
||||
onDelete: (id) => chat.deleteConversation(id),
|
||||
onRename: (id, title) => chat.renameConversation(id, title)
|
||||
}
|
||||
}
|
||||
: undefined
|
||||
|
||||
+36
-4
@@ -1,6 +1,7 @@
|
||||
import {
|
||||
WindmillApiError,
|
||||
WindmillChatApi,
|
||||
type ConversationKind,
|
||||
type FlowConversation,
|
||||
type FlowConversationMessage
|
||||
} from './api'
|
||||
@@ -18,6 +19,7 @@ import type {
|
||||
} from './types'
|
||||
import {
|
||||
conversationTitle,
|
||||
truncateTitle,
|
||||
errorResultMessage,
|
||||
extractChatAnswer,
|
||||
isAbortError,
|
||||
@@ -59,6 +61,8 @@ class ChatImpl implements Chat {
|
||||
#state: ChatState
|
||||
#turn: Turn | undefined
|
||||
#page = 1
|
||||
/** The kind the caller last listed, so the refresh after a new turn lists the same rows. */
|
||||
#conversationKind: ConversationKind | undefined
|
||||
#persistTimer: ReturnType<typeof setTimeout> | undefined
|
||||
|
||||
constructor(options: ChatOptions) {
|
||||
@@ -229,15 +233,21 @@ class ChatImpl implements Chat {
|
||||
}
|
||||
|
||||
loadConversations = async (
|
||||
options: { page?: number; perPage?: number } = {}
|
||||
options: { page?: number; perPage?: number; kind?: ConversationKind } = {}
|
||||
): Promise<Conversation[]> => {
|
||||
const page = options.page ?? 1
|
||||
// A different kind is a different listing: its first rows replace the held ones, on
|
||||
// whichever page they were asked for.
|
||||
const kindChanged = 'kind' in options && options.kind !== this.#conversationKind
|
||||
if ('kind' in options) this.#conversationKind = options.kind
|
||||
const kind = this.#conversationKind
|
||||
let conversations: Conversation[]
|
||||
if (this.#state.history === 'server') {
|
||||
try {
|
||||
const rows = await this.#api.listConversations(this.#config.flowPath, {
|
||||
page,
|
||||
perPage: options.perPage ?? this.#config.pageSize
|
||||
perPage: options.perPage ?? this.#config.pageSize,
|
||||
kind
|
||||
})
|
||||
conversations = rows.map(fromConversation)
|
||||
} catch (e) {
|
||||
@@ -247,10 +257,13 @@ class ChatImpl implements Chat {
|
||||
} else {
|
||||
conversations = this.#state.history === 'local' ? this.#local.listConversations() : []
|
||||
}
|
||||
// Another kind was asked for while this list was on its way: its rows are not the
|
||||
// listing any more, whichever response lands last.
|
||||
if (kind !== this.#conversationKind) return conversations
|
||||
const known = new Set(this.#state.conversations.map((c) => c.id))
|
||||
this.#set({
|
||||
conversations:
|
||||
page === 1
|
||||
page === 1 || kindChanged
|
||||
? conversations
|
||||
: [...this.#state.conversations, ...conversations.filter((c) => !known.has(c.id))]
|
||||
})
|
||||
@@ -273,6 +286,24 @@ class ChatImpl implements Chat {
|
||||
this.#set({ conversations: this.#state.conversations.filter((c) => c.id !== conversationId) })
|
||||
}
|
||||
|
||||
renameConversation = async (conversationId: string, title: string): Promise<void> => {
|
||||
// Cut here as the server cuts, so the title shown is the one stored.
|
||||
const trimmed = truncateTitle(title.trim())
|
||||
if (!trimmed) return
|
||||
if (this.#state.history === 'server') {
|
||||
await this.#api.renameConversation(conversationId, trimmed)
|
||||
} else if (this.#state.history === 'local') {
|
||||
this.#local.renameConversation(conversationId, trimmed)
|
||||
}
|
||||
// Patched in place: the server keeps `updated_at` on a rename, so the list order the
|
||||
// next load returns is the one shown now.
|
||||
this.#set({
|
||||
conversations: this.#state.conversations.map((c) =>
|
||||
c.id === conversationId ? { ...c, title: trimmed } : c
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
loadOlderMessages = async (): Promise<void> => {
|
||||
const conversationId = this.#state.conversationId
|
||||
if (
|
||||
@@ -734,7 +765,8 @@ function fromConversation(row: FlowConversation): Conversation {
|
||||
id: row.id,
|
||||
title: row.title ?? undefined,
|
||||
createdAt: row.created_at,
|
||||
updatedAt: row.updated_at
|
||||
updatedAt: row.updated_at,
|
||||
isTest: row.is_test
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -4,6 +4,8 @@ export interface LocalHistory {
|
||||
listConversations(): Conversation[]
|
||||
getMessages(conversationId: string): ChatMessage[]
|
||||
upsertConversation(conversation: Conversation): void
|
||||
/** Changes a stored conversation's title in place; unlike `upsertConversation`, its position is kept. */
|
||||
renameConversation(conversationId: string, title: string): void
|
||||
saveMessages(conversationId: string, messages: ChatMessage[]): void
|
||||
deleteConversation(conversationId: string): void
|
||||
}
|
||||
@@ -55,6 +57,11 @@ export function createLocalHistory(storage: StorageLike | undefined, key: string
|
||||
}
|
||||
write(s)
|
||||
},
|
||||
renameConversation(id, title) {
|
||||
const s = read()
|
||||
s.conversations = s.conversations.map((c) => (c.id === id ? { ...c, title } : c))
|
||||
write(s)
|
||||
},
|
||||
saveMessages(id, messages) {
|
||||
const s = read()
|
||||
s.messages[id] = messages.map((m) => ({ ...m, pending: false }))
|
||||
|
||||
@@ -5,6 +5,7 @@ export {
|
||||
WindmillApiError,
|
||||
readServerSentEvents,
|
||||
type WindmillChatApiOptions,
|
||||
type ConversationKind,
|
||||
type FlowConversation,
|
||||
type FlowConversationMessage,
|
||||
type JobUpdateEvent,
|
||||
|
||||
@@ -11,6 +11,7 @@ export type UseWindmillChat = ChatState &
|
||||
| 'selectConversation'
|
||||
| 'loadConversations'
|
||||
| 'deleteConversation'
|
||||
| 'renameConversation'
|
||||
| 'loadOlderMessages'
|
||||
> & { chat: Chat }
|
||||
|
||||
@@ -65,6 +66,7 @@ export function useWindmillChat(options: ChatOptions): UseWindmillChat {
|
||||
selectConversation: chat.selectConversation,
|
||||
loadConversations: chat.loadConversations,
|
||||
deleteConversation: chat.deleteConversation,
|
||||
renameConversation: chat.renameConversation,
|
||||
loadOlderMessages: chat.loadOlderMessages
|
||||
}),
|
||||
[state, chat]
|
||||
|
||||
+16
-1
@@ -52,6 +52,11 @@ export interface Conversation {
|
||||
title: string | undefined
|
||||
createdAt: string
|
||||
updatedAt: string
|
||||
/**
|
||||
* Started from the flow editor's test panel rather than a deployed run. Known once the
|
||||
* server has listed the conversation; unset for one only this client has seen.
|
||||
*/
|
||||
isTest?: boolean
|
||||
}
|
||||
|
||||
export interface ChatState {
|
||||
@@ -128,8 +133,18 @@ export interface Chat {
|
||||
stop(): Promise<void>
|
||||
newConversation(): void
|
||||
selectConversation(conversationId: string): Promise<void>
|
||||
loadConversations(options?: { page?: number; perPage?: number }): Promise<Conversation[]>
|
||||
/**
|
||||
* `kind` narrows server history to the flow editor's test chats, the deployed flow's
|
||||
* own (the server's default), or both. Local history has no test chats and ignores it.
|
||||
*/
|
||||
loadConversations(options?: {
|
||||
page?: number
|
||||
perPage?: number
|
||||
kind?: 'test' | 'deployed' | 'all'
|
||||
}): Promise<Conversation[]>
|
||||
deleteConversation(conversationId: string): Promise<void>
|
||||
/** Sets a conversation's title. The list keeps its order: only a turn moves a conversation. */
|
||||
renameConversation(conversationId: string, title: string): Promise<void>
|
||||
loadOlderMessages(): Promise<void>
|
||||
/** Stops background work (stream, polling) and writes local history out. The chat stays usable. */
|
||||
destroy(): void
|
||||
|
||||
@@ -69,6 +69,12 @@ export function conversationTitle(firstMessage: string): string {
|
||||
return chars.length > 25 ? `${chars.slice(0, 25).join('')}...` : firstMessage
|
||||
}
|
||||
|
||||
/** The server's bound on a typed title: 252 characters plus an ellipsis fits its 255-char column. */
|
||||
export function truncateTitle(title: string): string {
|
||||
const chars = Array.from(title)
|
||||
return chars.length > 252 ? `${chars.slice(0, 252).join('')}...` : title
|
||||
}
|
||||
|
||||
export function sleep(ms: number, signal?: AbortSignal): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (signal?.aborted) return reject(abortError())
|
||||
|
||||
@@ -414,6 +414,112 @@ describe('createChat with server history', () => {
|
||||
expect(chat.getState().conversations.map((c) => c.id)).toEqual(['c1', 'c2'])
|
||||
})
|
||||
|
||||
test('lists one kind of conversation and carries which kind each one is', async () => {
|
||||
const row = (id: string, is_test: boolean) => ({
|
||||
id,
|
||||
workspace_id: 'ws',
|
||||
flow_path: FLOW,
|
||||
title: id,
|
||||
created_at: '2026-01-01T00:00:00Z',
|
||||
updated_at: '2026-01-01T00:00:00Z',
|
||||
created_by: 'admin',
|
||||
is_test
|
||||
})
|
||||
const { fetch, calls } = fetchMock((c) =>
|
||||
c.url.pathname === '/api/w/ws/flow_conversations/list'
|
||||
? json(c.url.searchParams.get('kind') === 'test' ? [row('t1', true)] : [row('d1', false)])
|
||||
: undefined
|
||||
)
|
||||
const chat = createChat(options({}, fetch))
|
||||
await chat.loadConversations()
|
||||
expect(calls[0].url.searchParams.has('kind')).toBe(false)
|
||||
expect(chat.getState().conversations.map((c) => [c.id, c.isTest])).toEqual([['d1', false]])
|
||||
await chat.loadConversations({ kind: 'test' })
|
||||
expect(calls[1].url.searchParams.get('kind')).toBe('test')
|
||||
expect(chat.getState().conversations.map((c) => [c.id, c.isTest])).toEqual([['t1', true]])
|
||||
})
|
||||
|
||||
test('a list for a kind no longer asked for does not replace the newer one', async () => {
|
||||
const row = (id: string, is_test: boolean) => ({
|
||||
id,
|
||||
workspace_id: 'ws',
|
||||
flow_path: FLOW,
|
||||
title: id,
|
||||
created_at: '2026-01-01T00:00:00Z',
|
||||
updated_at: '2026-01-01T00:00:00Z',
|
||||
created_by: 'admin',
|
||||
is_test
|
||||
})
|
||||
const { fetch } = fetchMock((c) => {
|
||||
if (c.url.pathname !== '/api/w/ws/flow_conversations/list') return undefined
|
||||
if (c.url.searchParams.get('kind') === 'test') {
|
||||
return new Promise<Response>((r) => setTimeout(() => r(json([row('t1', true)])), 50))
|
||||
}
|
||||
return json([row('d1', false)])
|
||||
})
|
||||
const chat = createChat(options({}, fetch))
|
||||
const slow = chat.loadConversations({ kind: 'test' })
|
||||
await chat.loadConversations({ kind: 'deployed' })
|
||||
await slow
|
||||
expect(chat.getState().conversations.map((c) => c.id)).toEqual(['d1'])
|
||||
// Another kind asked for on a later page starts its own listing rather than appending.
|
||||
await chat.loadConversations({ page: 2, kind: 'test' })
|
||||
expect(chat.getState().conversations.map((c) => c.id)).toEqual(['t1'])
|
||||
})
|
||||
|
||||
test('the refresh after a new turn lists the kind last asked for', async () => {
|
||||
const { fetch, calls } = fetchMock(
|
||||
run,
|
||||
(c) =>
|
||||
c.url.pathname === streamPath
|
||||
? sse([{ type: 'update', completed: true, only_result: { output: 'Hello', messages: [] } }])
|
||||
: undefined,
|
||||
(c) =>
|
||||
c.method === 'GET' && c.url.pathname.endsWith('/messages')
|
||||
? json([messageRow(11, 'user', 'hi'), messageRow(12, 'assistant', 'Hello', { job_id: 'agent-job' })])
|
||||
: undefined,
|
||||
(c) => (c.url.pathname === '/api/w/ws/flow_conversations/list' ? json([]) : undefined)
|
||||
)
|
||||
const chat = createChat(options({}, fetch))
|
||||
await chat.loadConversations({ kind: 'test' })
|
||||
await chat.sendMessage('hi')
|
||||
const lists = calls.filter((c) => c.url.pathname === '/api/w/ws/flow_conversations/list')
|
||||
expect(lists.length).toBeGreaterThan(1)
|
||||
expect(lists.every((c) => c.url.searchParams.get('kind') === 'test')).toBe(true)
|
||||
})
|
||||
|
||||
test('renaming a conversation keeps its place in the list', async () => {
|
||||
const row = (id: string) => ({
|
||||
id,
|
||||
workspace_id: 'ws',
|
||||
flow_path: FLOW,
|
||||
title: id,
|
||||
created_at: '2026-01-01T00:00:00Z',
|
||||
updated_at: '2026-01-01T00:00:00Z',
|
||||
created_by: 'admin',
|
||||
is_test: false
|
||||
})
|
||||
const { fetch, calls } = fetchMock(
|
||||
(c) => (c.url.pathname === '/api/w/ws/flow_conversations/list' ? json([row('c1'), row('c2')]) : undefined),
|
||||
(c) =>
|
||||
c.method === 'POST' && c.url.pathname === '/api/w/ws/flow_conversations/update/c2'
|
||||
? text('Conversation c2 updated')
|
||||
: undefined
|
||||
)
|
||||
const chat = createChat(options({}, fetch))
|
||||
await chat.loadConversations()
|
||||
await chat.renameConversation('c2', ' Budget review ')
|
||||
expect(calls[1].body).toEqual({ title: 'Budget review' })
|
||||
expect(chat.getState().conversations.map((c) => [c.id, c.title])).toEqual([
|
||||
['c1', 'c1'],
|
||||
['c2', 'Budget review']
|
||||
])
|
||||
// Cut as the server cuts, so what is shown is what is stored.
|
||||
await chat.renameConversation('c2', 'x'.repeat(300))
|
||||
expect(chat.getState().conversations[1].title).toBe('x'.repeat(252) + '...')
|
||||
expect(calls[2].body).toEqual({ title: 'x'.repeat(252) + '...' })
|
||||
})
|
||||
|
||||
test('a turn started right after stop() is not touched by the stop sync', async () => {
|
||||
let jobs = 0
|
||||
const { fetch } = fetchMock(
|
||||
@@ -726,6 +832,27 @@ describe('createChat with server history', () => {
|
||||
expect((await again.loadConversations()).map((c) => c.id)).toEqual([newer, older])
|
||||
})
|
||||
|
||||
test('renaming a local conversation persists the title without reordering history', async () => {
|
||||
const storage = memoryStorage()
|
||||
const { fetch, calls } = fetchMock(run, (c) =>
|
||||
c.url.pathname === streamPath ? sse([{ type: 'update', completed: true, only_result: 'ok' }]) : undefined
|
||||
)
|
||||
const chat = createChat(options({ token: 'tok', storage }, fetch))
|
||||
await chat.sendMessage('older')
|
||||
const older = chat.getState().conversationId!
|
||||
chat.newConversation()
|
||||
await chat.sendMessage('newer')
|
||||
const newer = chat.getState().conversationId!
|
||||
const before = calls.length
|
||||
await chat.renameConversation(older, 'Renamed')
|
||||
expect(calls.length).toBe(before)
|
||||
const again = createChat(options({ token: 'tok', storage }, fetch))
|
||||
expect((await again.loadConversations()).map((c) => [c.id, c.title])).toEqual([
|
||||
[newer, 'newer'],
|
||||
[older, 'Renamed']
|
||||
])
|
||||
})
|
||||
|
||||
test('destroying the chat mid-turn leaves it idle', async () => {
|
||||
const { fetch } = fetchMock(run, (c) =>
|
||||
c.url.pathname === streamPath
|
||||
|
||||
Generated
+2
-2
File diff suppressed because one or more lines are too long
@@ -16,11 +16,12 @@ every workspace via the standard cached-resource-type sync, like other built-in
|
||||
- The brain config and tools are resolved at runtime from the resource
|
||||
(`windmill-worker/src/ai_executor.rs`): the brain is interpolated, so a nested provider `$res:`
|
||||
credential resolves automatically.
|
||||
- The step keeps only the flow-local inputs (`user_message`, `user_attachments`, `enabled_tools`)
|
||||
in its own `input_transforms`; the brain and tools stay in the resource (read-only in the step).
|
||||
`enabled_tools` says which of the roster this step may call, narrowing one use of a shared agent
|
||||
without touching the agent: an absent field carries every tool, a list carries the ones it names,
|
||||
and an empty list carries none.
|
||||
- The step keeps only the flow-local inputs (`user_message`, `user_attachments`, `enabled_tools`,
|
||||
and the history inputs `memory_id` and `previous_messages`) in its own `input_transforms`; the
|
||||
brain and tools stay in the resource (read-only in the step). `enabled_tools` says which of the
|
||||
roster this step may call, narrowing one use of a shared agent without touching the agent: an
|
||||
absent field carries every tool, a list carries the ones it names, and an empty list carries
|
||||
none.
|
||||
- The agent carries its tools' default input bindings verbatim as authored (static, AI-filled,
|
||||
or flow expressions), so saving round-trips losslessly. Each host flow overrides what it
|
||||
needs: `tool_inputs` stores per-tool overrides (a diff from the resource tool's own
|
||||
@@ -36,6 +37,58 @@ agent step); below the step's inputs, each tool gets a section with the standard
|
||||
input editors (prop picker included) and a read-only view of its code — edits persist into
|
||||
`tool_inputs`.
|
||||
|
||||
## Memory
|
||||
|
||||
Memory is split between three owners, so a saved agent carries whether it remembers and never
|
||||
which memory it is:
|
||||
|
||||
- **Agent: managed memory.** `memory` is a brain key, so it moves with a saved agent.
|
||||
`{ kind: window, context_length }` has Windmill store the conversation and replay its last N
|
||||
messages; `{ kind: off }` keeps none. An absent `memory` means off, the default: the editor turns
|
||||
it on when chat input is enabled. `auto` and `manual` are the older spellings and are still read.
|
||||
- **Run: memory id.** `flow_status.memory_id`, set when the run is queued: the chat conversation
|
||||
id, an app chat session id, or the `memory_id` run parameter. Any string is accepted, and one
|
||||
that is not a uuid is hashed to a v5 uuid scoped to the workspace and the flow the run started
|
||||
from (`memory_key` in `windmill-common/src/flow_conversations.rs`), so the same key in two flows
|
||||
names two memories. A uuid is used as is. Nothing is generated at save time, so schedules,
|
||||
webhooks, evals and plain runs pass no id and run stateless.
|
||||
- **Step: history inputs.** Flow-local, so they stay on a linked step. Each is read in one memory
|
||||
state only, and the editor offers it only there, the memory id behind a *Custom* toggle that
|
||||
writes the key only once it is on. With managed memory on, `memory_id` overrides the run's id,
|
||||
hashed the same way: a fixed value is one memory shared by every run, an expression such as
|
||||
`flow_input.customer_id` one memory per key, and an expression that evaluates to nothing runs
|
||||
stateless rather than falling back to the run's id. With memory off, `previous_messages` supplies
|
||||
the history itself. An older `auto` or `manual` memory reads neither, so the editor offers them
|
||||
only once the step is moved to the current settings, which the alert's button does. The editor
|
||||
never seeds a placeholder for either, because a present key is the step's choice, and a static
|
||||
empty value reads as unset.
|
||||
|
||||
The worker reconciles them once per agent invocation, nested agent tools included, in
|
||||
`resolve_history_source` (`windmill-worker/src/ai_executor.rs`):
|
||||
|
||||
1. A legacy `auto` or `manual` memory: read as the editor that wrote it ran it. `manual` replays
|
||||
its list; `auto` uses the run's memory id, else the id baked into it, else runs stateless.
|
||||
Neither history input is read. An `auto` without a count, or with 0, is off and read as such.
|
||||
2. Managed memory: the memory id is the step's, else the run's. With no memory id the agent runs
|
||||
stateless, and a step `previous_messages` is ignored.
|
||||
3. Memory off: the history is `previous_messages`, else nothing. Memory is neither read nor
|
||||
written, and a step `memory_id` is ignored.
|
||||
|
||||
Each ignored input and each stateless fallback is written to the job log.
|
||||
|
||||
Memory is stored per (memory id, step id), in `ai_agent_memory` or S3 at
|
||||
`memory/{workspace}/{memory id}/{step}.json`. The chat transcript (`flow_conversation_message`)
|
||||
always follows the run's id, even when a step sets its own. Nothing expires stored memory: deleting
|
||||
a chat conversation deletes its memory, and a memory named by a string id stays until it is
|
||||
overwritten.
|
||||
|
||||
Compatibility runs one way. New workers read every older shape. The editor rewrites a legacy step
|
||||
only when the author changes it, so a flow nobody edits keeps running on older workers, while a
|
||||
step saved with `window` or a history input needs a worker that knows them. An id an older editor
|
||||
baked into `memory` stays a fallback behind the run's id until the author chooses *Keep as memory
|
||||
id* or *Use the run's memory id*. In a chat flow it is dropped on save, since the conversation id
|
||||
always took precedence there.
|
||||
|
||||
## Drafts
|
||||
|
||||
The agent editor edits the resource through a **per-user resource draft** (`draft` table,
|
||||
|
||||
@@ -23,6 +23,8 @@ export interface SchemaProperty {
|
||||
pattern?: string
|
||||
default?: any
|
||||
enum?: EnumType
|
||||
/** Display names by stored value, for an enum's options or a one-of's variants. */
|
||||
enumLabels?: Record<string, string>
|
||||
contentEncoding?: 'base64' | 'binary'
|
||||
format?: string
|
||||
items?: {
|
||||
|
||||
@@ -209,6 +209,15 @@
|
||||
let tagKey = $derived(
|
||||
oneOf?.find((o) => Object.keys(o.properties ?? {})?.includes('kind')) ? 'kind' : 'label'
|
||||
)
|
||||
// `oneOfSelected` is resynced in an effect, one pass after the variants or the value change. A
|
||||
// variant that just left the list while the selection still names it, as when a value moves
|
||||
// off a legacy kind the list offered only for it, would render the nested form against nothing
|
||||
// for that pass and let it rewrite the value. The value's own tag settles it at once.
|
||||
let effectiveOneOfSelected = $derived.by(() => {
|
||||
if (oneOf?.some((o) => o.title === oneOfSelected)) return oneOfSelected
|
||||
const tag = value?.[tagKey]
|
||||
return oneOf?.some((o) => o.title === tag) ? tag : oneOfSelected
|
||||
})
|
||||
async function updateOneOfSelected(oneOf: SchemaProperty[] | undefined) {
|
||||
if (
|
||||
oneOf &&
|
||||
@@ -1112,7 +1121,7 @@
|
||||
{/if}
|
||||
{#if oneOf && oneOf.length >= 2}
|
||||
<ToggleButtonGroup
|
||||
selected={oneOfSelected}
|
||||
selected={effectiveOneOfSelected}
|
||||
wrap
|
||||
class="mb-4"
|
||||
disabled={disabled || oneOfLockedReason !== undefined}
|
||||
@@ -1143,12 +1152,16 @@
|
||||
>
|
||||
{#snippet children({ item })}
|
||||
{#each oneOf as obj}
|
||||
<ToggleButton value={obj.title ?? ''} label={obj.title} {item} />
|
||||
<ToggleButton
|
||||
value={obj.title ?? ''}
|
||||
label={extra?.['enumLabels']?.[obj.title ?? ''] ?? obj.title}
|
||||
{item}
|
||||
/>
|
||||
{/each}
|
||||
{/snippet}
|
||||
</ToggleButtonGroup>
|
||||
{#if oneOfSelected}
|
||||
{@const objIdx = oneOf.findIndex((o) => o.title === oneOfSelected)}
|
||||
{#if effectiveOneOfSelected}
|
||||
{@const objIdx = oneOf.findIndex((o) => o.title === effectiveOneOfSelected)}
|
||||
{@const obj = oneOf[objIdx]}
|
||||
{#if obj && obj.properties && Object.keys(obj.properties).length > 0}
|
||||
{#key redraw}
|
||||
@@ -1163,10 +1176,10 @@
|
||||
{workspace}
|
||||
bind:schema={
|
||||
() => ({
|
||||
properties: obj.properties ?? {},
|
||||
order: obj.order,
|
||||
properties: obj?.properties ?? {},
|
||||
order: obj?.order,
|
||||
$schema: '',
|
||||
required: obj.required ?? [],
|
||||
required: obj?.required ?? [],
|
||||
type: 'object'
|
||||
}),
|
||||
() => {
|
||||
@@ -1200,16 +1213,16 @@
|
||||
{workspace}
|
||||
hiddenArgs={['label', 'kind']}
|
||||
schema={{
|
||||
properties: obj.properties,
|
||||
order: obj.order,
|
||||
properties: obj?.properties ?? {},
|
||||
order: obj?.order,
|
||||
$schema: '',
|
||||
required: obj.required ?? [],
|
||||
required: obj?.required ?? [],
|
||||
type: 'object'
|
||||
}}
|
||||
bind:args={
|
||||
() => value,
|
||||
(v) => {
|
||||
value = { ...v, [tagKey]: oneOfSelected }
|
||||
value = { ...v, [tagKey]: effectiveOneOfSelected }
|
||||
}
|
||||
}
|
||||
{shouldDispatchChanges}
|
||||
|
||||
@@ -470,7 +470,7 @@
|
||||
)
|
||||
return jobId ?? ''
|
||||
}}
|
||||
hideSidebar={true}
|
||||
conversationKind="test"
|
||||
path={$pathStore}
|
||||
inputSchema={flowStore.val.schema}
|
||||
flowModules={flowStore.val.value?.modules}
|
||||
|
||||
@@ -19,6 +19,7 @@
|
||||
import DynamicInputHelpBox from './flows/content/DynamicInputHelpBox.svelte'
|
||||
import type { PropPickerWrapperContext } from './flows/propPicker/PropPickerWrapper.svelte'
|
||||
import { codeToStaticTemplate, getDefaultExpr } from './flows/utils.svelte'
|
||||
import { keepsManagedMemory } from './flows/agentFormFields'
|
||||
import SimpleEditor from './SimpleEditor.svelte'
|
||||
import { Button, ButtonType } from '$lib/components/common'
|
||||
import ToggleButtonGroup from '$lib/components/common/toggleButton-v2/ToggleButtonGroup.svelte'
|
||||
@@ -53,6 +54,8 @@
|
||||
label?: string
|
||||
/** Replaces the label header, so a setting's own toggle can name the field. */
|
||||
header?: Snippet
|
||||
/** Indent the input under the header's label, for a header that starts with a switch. */
|
||||
indentUnderHeader?: boolean
|
||||
/** Renders after the label: a button to unset the field, a badge. */
|
||||
labelExtra?: Snippet
|
||||
/** Drop the schema's description paragraph, for a form that carries it in a tooltip. */
|
||||
@@ -119,6 +122,7 @@
|
||||
argName = $bindable(),
|
||||
label = undefined,
|
||||
header = undefined,
|
||||
indentUnderHeader = true,
|
||||
labelExtra = undefined,
|
||||
hideDescription = false,
|
||||
subtleControls = false,
|
||||
@@ -863,7 +867,7 @@
|
||||
<!-- A custom header means a setting's toggle owns this field, so the input is
|
||||
indented under the toggle's label: `xs` switch (w-7) plus its ml-2. -->
|
||||
<div
|
||||
class="relative w-full {header ? 'pl-9' : ''}"
|
||||
class="relative w-full {header && indentUnderHeader ? 'pl-9' : ''}"
|
||||
onkeyup={handleKeyUp}
|
||||
transition:slideDynamic|global={{ duration: animateAppear ? 150 : 0 }}
|
||||
>
|
||||
@@ -1001,7 +1005,7 @@
|
||||
{chatInputEnabled}
|
||||
oneOfLockedReason={chatInputEnabled &&
|
||||
arg?.type === 'static' &&
|
||||
(arg.value as any)?.kind !== 'off'
|
||||
keepsManagedMemory(arg.value)
|
||||
? schema.properties[argName]?.lockOneOfWhenChatEnabled
|
||||
: undefined}
|
||||
otherArgs={Object.fromEntries(
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
import { getContext, untrack } from 'svelte'
|
||||
import type { FlowEditorContext } from './flows/types'
|
||||
import { evalValue } from './flows/utils.svelte'
|
||||
import { memoryPropertyFor } from './flows/flowInfers'
|
||||
import type { FlowModule } from '$lib/gen'
|
||||
import type { PickableProperties } from './flows/previousResults'
|
||||
import type SimpleEditor from './SimpleEditor.svelte'
|
||||
@@ -61,6 +62,9 @@
|
||||
* for a surface whose form cannot open a row at all. A schema key the field registry doesn't
|
||||
* know is kept, so a new one is never silently dropped. */
|
||||
let schemaKeys = $derived(Object.keys(schema?.properties ?? {}))
|
||||
// A legacy memory kind this step still holds stays one of the options, or the one-of field would
|
||||
// turn the test run's memory off.
|
||||
let isAgent = $derived((mod.value as { type?: string })?.type === 'aiagent')
|
||||
|
||||
let visibleKeys = $derived.by(() => {
|
||||
const all = schemaKeys
|
||||
@@ -71,7 +75,11 @@
|
||||
for (const key of openAgentFields(openFieldsKey)) visible.add(key)
|
||||
for (const key of runInputKeys) visible.add(key)
|
||||
const known = new Set(AGENT_FIELDS.map((f) => f.key))
|
||||
return all.filter((key) => !known.has(key) || visible.has(key))
|
||||
// Listed in the agent form's order rather than the schema's, so the two read the same.
|
||||
const position = new Map(AGENT_FIELDS.map((f, i) => [f.key, i]))
|
||||
return all
|
||||
.filter((key) => !known.has(key) || visible.has(key))
|
||||
.sort((a, b) => (position.get(a) ?? Infinity) - (position.get(b) ?? Infinity))
|
||||
})
|
||||
|
||||
let keys: string[] = $state([])
|
||||
@@ -182,7 +190,12 @@
|
||||
(v) => stepsInputArgs?.setStepInputArgs(mod.id, argName, v)
|
||||
}
|
||||
type={schema.properties[argName].type}
|
||||
oneOf={schema.properties[argName].oneOf}
|
||||
oneOf={isAgent && argName === 'memory'
|
||||
? memoryPropertyFor(
|
||||
schema.properties[argName],
|
||||
stepsInputArgs?.getStepInputArgs(mod.id, argName)
|
||||
)?.oneOf
|
||||
: schema.properties[argName].oneOf}
|
||||
required={schema?.required?.includes(argName)}
|
||||
pattern={schema.properties[argName].pattern}
|
||||
bind:editor={editor[argName]}
|
||||
|
||||
@@ -21,6 +21,7 @@
|
||||
type LinkedAgentDraft
|
||||
} from './flows/linkedAgentDrafts'
|
||||
import { AGENT_FLOW_LOCAL_KEYS } from './flows/agentResourceUtils'
|
||||
import { AGENT_HISTORY_KEYS } from './flows/agentFormFields'
|
||||
import { sendUserToast } from '$lib/toast'
|
||||
|
||||
interface Props {
|
||||
@@ -170,11 +171,21 @@
|
||||
}
|
||||
const agentVal = draft ? inlineAgentDraft(val, draft.args) : val
|
||||
|
||||
// `args` is built from the whole AI agent schema whatever the step is, so on a linked step
|
||||
// it carries every brain key as undefined even though the form renders only the flow-local
|
||||
// ones (`flowLocalAgentSchema`). Overlaying those would shadow the brain the draft just
|
||||
// supplied with nothing, so an inlined step takes only the inputs its form actually offers.
|
||||
const formKeys = draft ? (AGENT_FLOW_LOCAL_KEYS as readonly string[]) : Object.keys(args)
|
||||
// `args` spans the whole AI agent schema, so on a linked step it carries every brain key as
|
||||
// undefined; overlaying those would shadow the draft's brain, so an inlined step takes only
|
||||
// the inputs its form offers. A blank history input is unset, as on the step: an expression
|
||||
// evaluating to nothing reads as an empty memory id, and the step's transform is stale.
|
||||
const isBlank = (v: unknown) => v == undefined || v === '' || (Array.isArray(v) && !v.length)
|
||||
const formKeys = (
|
||||
draft ? (AGENT_FLOW_LOCAL_KEYS as readonly string[]) : Object.keys(args)
|
||||
).filter(
|
||||
(key) => !(AGENT_HISTORY_KEYS as readonly string[]).includes(key) || !isBlank(args[key])
|
||||
)
|
||||
const stepTransforms = Object.fromEntries(
|
||||
Object.entries((agentVal.input_transforms ?? {}) as Record<string, InputTransform>).filter(
|
||||
([key]) => !(AGENT_HISTORY_KEYS as readonly string[]).includes(key) || !isBlank(args[key])
|
||||
)
|
||||
)
|
||||
|
||||
// The test form only covers the schema it was given, and for a standalone agent that may be
|
||||
// the flow-local one (the agent editor shows the brain in its own form, not here). Take the
|
||||
@@ -182,9 +193,7 @@
|
||||
// in the form after the test panel mounted is what runs. A linked agent needs none of this:
|
||||
// the server reads its brain from the resource.
|
||||
const inputTransforms: { [key: string]: JavascriptTransform | InputTransform } = {
|
||||
...(agentVal.agent
|
||||
? {}
|
||||
: ((agentVal.input_transforms ?? {}) as Record<string, InputTransform>)),
|
||||
...(agentVal.agent ? {} : stepTransforms),
|
||||
...Object.fromEntries(
|
||||
formKeys.map((key) => [
|
||||
key,
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const { listMock } = vi.hoisted(() => ({ listMock: vi.fn() }))
|
||||
const { listMock, listMetricsMock } = vi.hoisted(() => ({
|
||||
listMock: vi.fn(),
|
||||
listMetricsMock: vi.fn()
|
||||
}))
|
||||
|
||||
vi.mock('./shared', () => ({
|
||||
createToolDef: (_schema: unknown, name: string, description: string) => ({
|
||||
@@ -10,7 +13,8 @@ vi.mock('./shared', () => ({
|
||||
}))
|
||||
|
||||
vi.mock('$lib/gen', () => ({
|
||||
WorkspaceService: { listDucklakes: listMock }
|
||||
WorkspaceService: { listDucklakes: listMock },
|
||||
DataMetricService: { listDataMetrics: listMetricsMock }
|
||||
}))
|
||||
|
||||
import { getDucklakeTools } from './ducklakeTools'
|
||||
@@ -31,7 +35,10 @@ function run(name: string, args: Record<string, unknown> = {}) {
|
||||
})
|
||||
}
|
||||
|
||||
beforeEach(() => listMock.mockReset())
|
||||
beforeEach(() => {
|
||||
listMock.mockReset()
|
||||
listMetricsMock.mockReset()
|
||||
})
|
||||
|
||||
describe('list_ducklakes', () => {
|
||||
it('returns the configured catalog names', async () => {
|
||||
@@ -51,3 +58,65 @@ describe('list_ducklakes', () => {
|
||||
expect(result).toContain('still draft the pipeline scripts')
|
||||
})
|
||||
})
|
||||
|
||||
describe('list_data_metrics', () => {
|
||||
it('forwards the filters and returns the declarations', async () => {
|
||||
listMetricsMock.mockResolvedValue({
|
||||
metrics: [
|
||||
{
|
||||
script_path: 'f/analytics/rev',
|
||||
table_path: 'main/main.orders',
|
||||
kind: 'measure',
|
||||
name: 'revenue',
|
||||
expr: 'sum(amount)',
|
||||
filter: 'not is_test'
|
||||
}
|
||||
]
|
||||
})
|
||||
const result = await run('list_data_metrics', {
|
||||
table: 'ducklake://main/main.orders',
|
||||
path_prefix: 'f/analytics',
|
||||
limit: 50
|
||||
})
|
||||
expect(listMetricsMock).toHaveBeenCalledWith({
|
||||
workspace: 'test-workspace',
|
||||
table: 'ducklake://main/main.orders',
|
||||
pathPrefix: 'f/analytics',
|
||||
perPage: 50
|
||||
})
|
||||
expect(JSON.parse(result).metrics[0]).toMatchObject({ name: 'revenue', expr: 'sum(amount)' })
|
||||
})
|
||||
|
||||
it('never reports an empty result as proof that nothing is declared', async () => {
|
||||
listMetricsMock.mockResolvedValue({ metrics: [] })
|
||||
const result = await run('list_data_metrics', {})
|
||||
// Unreadable declarations are omitted, not flagged, so absence is unprovable.
|
||||
expect(result).toContain('does not establish')
|
||||
expect(result).toContain('cannot read')
|
||||
})
|
||||
|
||||
// The server matches a lake-less name against nothing, so the readability hedge
|
||||
// would confirm "nothing is declared" for a filter worth retrying. The scheme is
|
||||
// optional on the way in, so the retry it names must not carry it back.
|
||||
it.each(['orders', 'ducklake://orders'])(
|
||||
'blames the missing lake, not readability, for table %s',
|
||||
async (table) => {
|
||||
listMetricsMock.mockResolvedValue({ metrics: [] })
|
||||
const result = await run('list_data_metrics', { table })
|
||||
expect(result).toContain('`<lake>/orders`')
|
||||
expect(result).not.toContain('cannot read')
|
||||
}
|
||||
)
|
||||
|
||||
it('warns that more declarations exist when the page is cut short', async () => {
|
||||
listMetricsMock.mockResolvedValue({
|
||||
// A cursor only comes back on a full page, never with an empty one.
|
||||
metrics: [{ table_path: 't', kind: 'measure', name: 'n', script_path: 's' }],
|
||||
next_cursor: { table_path: 't', kind: 'measure', name: 'n', script_path: 's' }
|
||||
})
|
||||
const result = await run('list_data_metrics', {})
|
||||
// Without this the model reads a partial page as "no such measure" and
|
||||
// re-derives a number that disagrees with the declared one.
|
||||
expect(result).toContain('rather than concluding a measure is undeclared')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,17 +1,19 @@
|
||||
import { z } from 'zod'
|
||||
import { WorkspaceService } from '$lib/gen'
|
||||
import { DataMetricService, WorkspaceService } from '$lib/gen'
|
||||
import { createToolDef, type Tool } from './shared'
|
||||
|
||||
/**
|
||||
* Workspace-scoped DuckLake readiness tool, the pipeline counterpart to
|
||||
* `list_datatables` in `datatableTools.ts`.
|
||||
* Workspace-scoped DuckLake tools, the pipeline counterpart to `list_datatables`
|
||||
* in `datatableTools.ts`.
|
||||
*
|
||||
* A data pipeline materializes DuckLake tables and reads/writes S3 assets, which
|
||||
* only work once the workspace has object storage + a DuckLake catalog
|
||||
* configured. This tool lets the chat detect that prerequisite (and warn with
|
||||
* role-appropriate next steps) instead of silently producing a pipeline that
|
||||
* cannot run. It is a plain read gated only by workspace membership, so it needs
|
||||
* no app context and belongs in the global tool set.
|
||||
* configured. `list_ducklakes` lets the chat detect that prerequisite (and warn
|
||||
* with role-appropriate next steps) instead of silently producing a pipeline that
|
||||
* cannot run. `list_data_metrics` reads the declarations recorded against those
|
||||
* lake tables, not the tables themselves. Both are plain reads gated only by
|
||||
* workspace membership, so they need no app context and belong in the global tool
|
||||
* set.
|
||||
*/
|
||||
|
||||
/** List the names of the DuckLake catalogs configured in the workspace. */
|
||||
@@ -31,9 +33,78 @@ const listDucklakesToolDef = createToolDef(
|
||||
'List the DuckLake catalogs configured in this workspace, by name. Call this before building or deploying a data pipeline that materializes DuckLake tables or reads/writes S3 assets: if it returns none, the workspace has no object storage + DuckLake configured and the pipeline cannot run until a workspace admin sets it up. Returns names only.'
|
||||
)
|
||||
|
||||
const listDataMetricsSchema = z.object({
|
||||
table: z
|
||||
.string()
|
||||
.optional()
|
||||
.describe(
|
||||
'Only declarations on this DuckLake table, as `<lake>/<table>` or `<lake>/<schema>.<table>`, with or without the `ducklake://` scheme. A name with no lake matches nothing and comes back empty.'
|
||||
),
|
||||
path_prefix: z
|
||||
.string()
|
||||
.optional()
|
||||
.describe('Only declarations made by scripts under this path, e.g. `f/analytics`.'),
|
||||
limit: z
|
||||
.number()
|
||||
.int()
|
||||
.min(1)
|
||||
.max(1000)
|
||||
.optional()
|
||||
.describe('Max number of declarations to return. Defaults to 200.')
|
||||
})
|
||||
const listDataMetricsToolDef = createToolDef(
|
||||
listDataMetricsSchema,
|
||||
'list_data_metrics',
|
||||
'List the measures and dimensions declared on DuckLake tables (from `// measure` / `// dimension` annotations in deployed scripts). Call this before writing any aggregate query over a DuckLake table: a declared measure is the canonical definition of that number, and reproducing it yourself silently disagrees with it (a `revenue` measure typically excludes refunds or test rows). Use each returned `expr` verbatim, and when a measure has a `filter` write it as `expr FILTER (WHERE filter)` so measures with different predicates share one GROUP BY. Only declarations whose producing script you can read are returned, so what comes back is never proof of what exists: if the number you need is not here you may still write your own aggregate, but say that you found no declared measure for it rather than implying none exists.'
|
||||
)
|
||||
|
||||
// The endpoint drops declarations whose producing script the caller cannot read
|
||||
// (token scope + RLS on `script`), so an empty result means "none declared" or
|
||||
// "none readable by you" and the tool cannot tell which.
|
||||
const NO_DATA_METRICS_NOTE =
|
||||
'Nothing matched. That does not establish that nothing is declared: declarations whose producing script you cannot read are omitted from this list, not flagged. You may write your own aggregate, but tell the user you found no declared measure you can read rather than stating none is declared.'
|
||||
|
||||
// Well under the endpoint's 1000 cap: a full page is pretty-printed into the
|
||||
// chat context, and 1000 declarations would cost tens of thousands of tokens.
|
||||
const DEFAULT_DATA_METRICS_LIMIT = 200
|
||||
|
||||
/** The workspace DuckLake tools, for registration in global mode. */
|
||||
export function getDucklakeTools(): Tool<{}>[] {
|
||||
return [
|
||||
{
|
||||
def: listDataMetricsToolDef,
|
||||
planModeSafe: true,
|
||||
showDetails: true,
|
||||
fn: async ({ args, workspace, toolId, toolCallbacks }) => {
|
||||
const parsed = listDataMetricsSchema.parse(args)
|
||||
toolCallbacks.setToolStatus(toolId, { content: 'Listing declared measures...' })
|
||||
const limit = parsed.limit ?? DEFAULT_DATA_METRICS_LIMIT
|
||||
const { metrics, next_cursor } = await DataMetricService.listDataMetrics({
|
||||
workspace,
|
||||
table: parsed.table,
|
||||
pathPrefix: parsed.path_prefix,
|
||||
perPage: limit
|
||||
})
|
||||
// `canonical_table_path` expands a value only once it contains a `/`, so a bare
|
||||
// table name matches nothing — a retryable filter, not a permissions outcome.
|
||||
const bareTable = parsed.table?.replace('ducklake://', '')
|
||||
const emptyNote =
|
||||
bareTable && !bareTable.includes('/')
|
||||
? `Nothing matched \`${parsed.table}\`: a table filter must name its lake, as \`<lake>/${bareTable}\`. Re-call with the lake before concluding anything about what is declared.`
|
||||
: NO_DATA_METRICS_NOTE
|
||||
const note = next_cursor
|
||||
? `More declarations exist beyond the first ${limit}. Re-call with table/path_prefix to target what you are looking for, or with a higher limit (max 1000) for the rest of the list, rather than concluding a measure is undeclared.`
|
||||
: metrics.length === 0
|
||||
? emptyNote
|
||||
: undefined
|
||||
const result = JSON.stringify({ metrics, ...(note ? { note } : {}) }, null, 2)
|
||||
toolCallbacks.setToolStatus(toolId, {
|
||||
content: `Listed ${metrics.length} declared measure(s)/dimension(s)`,
|
||||
result
|
||||
})
|
||||
return result
|
||||
}
|
||||
},
|
||||
{
|
||||
def: listDucklakesToolDef,
|
||||
planModeSafe: true,
|
||||
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -31,6 +31,24 @@ const CATALOG = [
|
||||
properties: { page: { type: 'integer' }, per_page: { type: 'integer' } }
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'listDataMetrics',
|
||||
description: 'List declared measures and dimensions',
|
||||
instructions: '',
|
||||
path: '/w/{workspace}/data_metrics/list',
|
||||
method: 'GET'
|
||||
},
|
||||
{
|
||||
name: 'listQueue',
|
||||
description: 'List queued jobs',
|
||||
instructions: 'List the jobs waiting in the queue',
|
||||
path: '/w/{workspace}/jobs/queue/list',
|
||||
method: 'GET',
|
||||
query_params_schema: {
|
||||
type: 'object',
|
||||
properties: { running: { type: 'boolean' }, per_page: { type: 'integer' } }
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'getJobUpdates',
|
||||
description: 'Get job updates',
|
||||
@@ -177,11 +195,12 @@ beforeEach(() => {
|
||||
|
||||
describe('search_api_endpoints', () => {
|
||||
it('matches on name/path tokens, plural-insensitively, and excludes covered endpoints', async () => {
|
||||
const result = await run('search_api_endpoints', { query: 'worker' })
|
||||
expect(result.matches.map((m: any) => m.name)).toEqual(['listWorkers'])
|
||||
expect(result.matches[0].endpoint).toBe('GET /workers/list')
|
||||
expect(result.matches[0].params).toEqual(['page', 'per_page'])
|
||||
expect(result.matches[0].instructions).toContain('ping status')
|
||||
// Singular "job" matches the plural "jobs" path segment.
|
||||
const result = await run('search_api_endpoints', { query: 'list queued job' })
|
||||
expect(result.matches[0].name).toBe('listQueue')
|
||||
expect(result.matches[0].endpoint).toBe('GET /w/{workspace}/jobs/queue/list')
|
||||
expect(result.matches[0].params).toEqual(['running', 'per_page'])
|
||||
expect(result.matches[0].instructions).toContain('waiting in the queue')
|
||||
|
||||
const flows = await run('search_api_endpoints', { query: 'create flow' })
|
||||
expect(flows.matches.map((m: any) => m.name)).not.toContain('createFlow')
|
||||
@@ -191,8 +210,11 @@ describe('search_api_endpoints', () => {
|
||||
it('returns endpoint categories when nothing matches', async () => {
|
||||
const result = await run('search_api_endpoints', { query: 'kubernetes' })
|
||||
expect(result.matches).toEqual([])
|
||||
expect(result.hint).toContain('workers')
|
||||
expect(result.hint).toContain('jobs')
|
||||
expect(result.hint).toContain('jobs_u')
|
||||
// Categories are built from the uncovered endpoints only, so a covered one
|
||||
// must not be advertised as somewhere to retry.
|
||||
expect(result.hint).not.toContain('workers')
|
||||
expect(result.hint).not.toContain('data_metrics')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -253,6 +275,21 @@ describe('call_api_get', () => {
|
||||
expect(search.matches.map((m: any) => m.name)).not.toContain('getScriptByPath')
|
||||
})
|
||||
|
||||
it('refuses the worker and data-metric reads, pointing at their dedicated tools', async () => {
|
||||
for (const [name, tool, query] of [
|
||||
['listWorkers', 'list_workers', 'workers'],
|
||||
['listDataMetrics', 'list_data_metrics', 'data metrics']
|
||||
]) {
|
||||
const result = await run('call_api_get', { name })
|
||||
expect(result.success).toBe(false)
|
||||
expect(result.error).toContain(tool)
|
||||
|
||||
const search = await run('search_api_endpoints', { query })
|
||||
expect(search.matches.map((m: any) => m.name)).not.toContain(name)
|
||||
expect(search.covered_by_dedicated_tools?.join(' ')).toContain(tool)
|
||||
}
|
||||
})
|
||||
|
||||
it('refuses variable reads so variable values never reach the model', async () => {
|
||||
const result = await run('call_api_get', { name: 'getVariable' })
|
||||
expect(result.success).toBe(false)
|
||||
@@ -273,12 +310,14 @@ describe('call_api_get', () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
headers: new Headers({ 'content-type': 'application/json' }),
|
||||
json: async () => [{ worker: 'w1' }]
|
||||
json: async () => [{ id: 'job-1' }]
|
||||
})
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
const result = await run('call_api_get', { name: 'listWorkers', params: { page: 2 } })
|
||||
expect(fetchMock).toHaveBeenCalledWith('/api/workers/list?page=2', { method: 'GET' })
|
||||
expect(result).toEqual({ success: true, data: [{ worker: 'w1' }] })
|
||||
const result = await run('call_api_get', { name: 'listQueue', params: { running: true } })
|
||||
expect(fetchMock).toHaveBeenCalledWith('/api/w/test-ws/jobs/queue/list?running=true', {
|
||||
method: 'GET'
|
||||
})
|
||||
expect(result).toEqual({ success: true, data: [{ id: 'job-1' }] })
|
||||
})
|
||||
})
|
||||
|
||||
@@ -305,7 +344,7 @@ describe('call_api_endpoint', () => {
|
||||
})
|
||||
|
||||
it('redirects GET endpoints to call_api_get', async () => {
|
||||
const result = await run('call_api_endpoint', { name: 'listWorkers' })
|
||||
const result = await run('call_api_endpoint', { name: 'listQueue' })
|
||||
expect(result.error).toContain('call_api_get')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -58,6 +58,8 @@ const COVERED_ENDPOINTS: Record<string, string> = {
|
||||
searchDocs: 'search_docs',
|
||||
readDocsPage: 'read_docs_page',
|
||||
listJobs: 'list_runs',
|
||||
listWorkers: 'list_workers',
|
||||
listDataMetrics: 'list_data_metrics',
|
||||
getJob: 'get_run',
|
||||
getJobLogs: 'get_run',
|
||||
runScriptPreviewAndWaitResult: 'test_run_script'
|
||||
@@ -231,7 +233,7 @@ const searchApiEndpointsSchema = z.object({
|
||||
query: z
|
||||
.string()
|
||||
.describe(
|
||||
'Keywords matched against endpoint names, paths, and descriptions (e.g. "workers", "queue", "run flow"). Jobs are called "runs" in the UI.'
|
||||
'Keywords matched against endpoint names, paths, and descriptions (e.g. "queue", "run flow", "audit log"). Jobs are called "runs" in the UI.'
|
||||
)
|
||||
})
|
||||
|
||||
@@ -264,7 +266,7 @@ export const apiCatalogTools: Tool<{}>[] = [
|
||||
def: createToolDef(
|
||||
searchApiEndpointsSchema,
|
||||
'search_api_endpoints',
|
||||
'Search the Windmill REST API endpoint catalog for operations no dedicated tool covers (workers, queue state, job details, running deployed items, deletions, ...). Returns endpoint names to pass to call_api_get or call_api_endpoint.'
|
||||
'Search the Windmill REST API endpoint catalog for operations no dedicated tool covers (queue state, job details, running deployed items, deletions, ...). Returns endpoint names to pass to call_api_get or call_api_endpoint.'
|
||||
),
|
||||
planModeSafe: true,
|
||||
fn: async ({ args, workspace, toolId, toolCallbacks }) => {
|
||||
|
||||
@@ -256,6 +256,9 @@ vi.mock('$lib/gen', async () => {
|
||||
createVariable: vi.fn(async () => 'created'),
|
||||
updateVariable: vi.fn(async () => 'updated')
|
||||
}),
|
||||
WorkerService: wrapService(actual.WorkerService, {
|
||||
listWorkers: vi.fn(async () => [])
|
||||
}),
|
||||
FolderService: wrapService(actual.FolderService, {
|
||||
createFolder: vi.fn(async () => 'created')
|
||||
}),
|
||||
@@ -264,6 +267,17 @@ vi.mock('$lib/gen', async () => {
|
||||
const user = whoamiByWorkspace.get(workspace)
|
||||
if (!user) throw new Error(`not a member of ${workspace}`)
|
||||
return user
|
||||
}),
|
||||
// `refreshSuperadmin` cancels the previous in-flight call, so this stands in for
|
||||
// the CancelablePromise the real client returns.
|
||||
globalWhoami: vi.fn(() => {
|
||||
const pending: any = Promise.resolve({
|
||||
email: 'devops@windmill.dev',
|
||||
super_admin: false,
|
||||
devops: true
|
||||
})
|
||||
pending.cancel = () => {}
|
||||
return pending
|
||||
})
|
||||
}),
|
||||
DraftService: wrapService(actual.DraftService, {
|
||||
@@ -389,9 +403,10 @@ import {
|
||||
ScheduleService,
|
||||
ScriptService,
|
||||
UserService,
|
||||
VariableService
|
||||
VariableService,
|
||||
WorkerService
|
||||
} from '$lib/gen'
|
||||
import { superadmin, userStore, usersWorkspaceStore } from '$lib/stores'
|
||||
import { devopsRole, superadmin, userStore, usersWorkspaceStore } from '$lib/stores'
|
||||
import { processSecretArgs } from '$lib/components/secretArgUtils'
|
||||
import { clearWorkspaceRoleCache } from '$lib/user'
|
||||
import { get } from 'svelte/store'
|
||||
@@ -738,6 +753,102 @@ describe('global AI tools', () => {
|
||||
)
|
||||
})
|
||||
|
||||
it('lists workers with the diagnostic fields only', async () => {
|
||||
vi.mocked(WorkerService.listWorkers).mockResolvedValueOnce([
|
||||
{
|
||||
worker: 'wk-1',
|
||||
worker_instance: 'host-1',
|
||||
worker_group: 'gpu',
|
||||
custom_tags: ['gpu'],
|
||||
last_ping: 3,
|
||||
jobs_executed: 12,
|
||||
started_at: '2024-01-01T00:00:00Z',
|
||||
ip: '10.0.0.1',
|
||||
wm_version: 'v1',
|
||||
memory: 123,
|
||||
occupancy_rate: 0.5
|
||||
}
|
||||
])
|
||||
|
||||
const result = await callGlobalTool('list_workers', {})
|
||||
|
||||
expect(JSON.parse(result).workers).toEqual([
|
||||
{
|
||||
worker: 'wk-1',
|
||||
worker_group: 'gpu',
|
||||
custom_tags: ['gpu'],
|
||||
last_ping: 3,
|
||||
jobs_executed: 12
|
||||
}
|
||||
])
|
||||
// Page telemetry must stay out of the model's context.
|
||||
expect(result).not.toContain('occupancy_rate')
|
||||
expect(result).not.toContain('10.0.0.1')
|
||||
})
|
||||
|
||||
it('says so when the worker page is cut short', async () => {
|
||||
vi.mocked(WorkerService.listWorkers).mockResolvedValueOnce(
|
||||
Array(100).fill({
|
||||
worker: 'wk',
|
||||
worker_group: 'default',
|
||||
custom_tags: [],
|
||||
last_ping: 1,
|
||||
jobs_executed: 0
|
||||
}) as any
|
||||
)
|
||||
|
||||
const result = await callGlobalTool('list_workers', {})
|
||||
|
||||
// A full page is indistinguishable from the whole fleet, and the model reasons
|
||||
// about tag coverage from this list.
|
||||
expect(JSON.parse(result).note).toContain('Only the first 100 workers')
|
||||
})
|
||||
|
||||
describe('list_workers with nothing to show', () => {
|
||||
afterEach(() => {
|
||||
superadmin.set(undefined)
|
||||
devopsRole.set(undefined)
|
||||
})
|
||||
|
||||
it('never reports an empty list as an absence to a caller workers can be hidden from', async () => {
|
||||
superadmin.set(false)
|
||||
devopsRole.set(false)
|
||||
vi.mocked(WorkerService.listWorkers).mockResolvedValueOnce([])
|
||||
|
||||
const result = await callGlobalTool('list_workers', {})
|
||||
|
||||
// An instance hiding workers from a non-devops caller answers with an empty
|
||||
// list, so absence is unprovable here.
|
||||
expect(result).toContain('does NOT establish that no workers are running')
|
||||
expect(result).toContain('devops role')
|
||||
expect(result).not.toContain('"workers"')
|
||||
})
|
||||
|
||||
it('reports an empty list as an absence to a devops caller', async () => {
|
||||
devopsRole.set('devops@windmill.dev')
|
||||
vi.mocked(WorkerService.listWorkers).mockResolvedValueOnce([])
|
||||
|
||||
const result = await callGlobalTool('list_workers', {})
|
||||
|
||||
// Nothing is hidden from this caller, so hedging would withhold the answer a
|
||||
// stuck queue is waiting on.
|
||||
expect(result).toContain('No workers are connected')
|
||||
expect(result).not.toContain('does NOT establish')
|
||||
})
|
||||
|
||||
it('resolves the role before deciding, rather than reading unloaded stores as no role', async () => {
|
||||
// Both stores start undefined; without the refresh a devops caller whose whoami
|
||||
// has not landed yet is hedged at instead of answered.
|
||||
expect(get(superadmin)).toBeUndefined()
|
||||
expect(get(devopsRole)).toBeUndefined()
|
||||
vi.mocked(WorkerService.listWorkers).mockResolvedValueOnce([])
|
||||
|
||||
const result = await callGlobalTool('list_workers', {})
|
||||
|
||||
expect(result).toContain('No workers are connected')
|
||||
})
|
||||
})
|
||||
|
||||
it('returns args, result and logs of a run in one call', async () => {
|
||||
const result = await callGlobalTool('get_run', { id: 'job-123' })
|
||||
|
||||
|
||||
@@ -17,7 +17,8 @@ import {
|
||||
ScriptService,
|
||||
SqsTriggerService,
|
||||
VariableService,
|
||||
WebsocketTriggerService
|
||||
WebsocketTriggerService,
|
||||
WorkerService
|
||||
} from '$lib/gen'
|
||||
import { createTwoFilesPatch } from 'diff'
|
||||
import { deepEqual } from 'fast-equals'
|
||||
@@ -179,6 +180,7 @@ import {
|
||||
workspaceStore
|
||||
} from '$lib/stores'
|
||||
import { getWorkspaceRole, type RoleLookup } from '$lib/user'
|
||||
import { refreshSuperadmin } from '$lib/refreshUser'
|
||||
import { get } from 'svelte/store'
|
||||
import {
|
||||
canonicalDraftSideValue,
|
||||
@@ -724,6 +726,17 @@ const listRunsSchema = z.object({
|
||||
.describe('Max number of runs to return, most recent first. Defaults to 30.')
|
||||
})
|
||||
|
||||
// `GET /workers/list` hides workers from a caller without the devops role by
|
||||
// returning an empty list, not an error, when HIDE_WORKERS_FOR_NON_ADMINS is set.
|
||||
// The flag is not visible here, so absence is only provable for a devops or
|
||||
// superadmin caller; every other caller gets the hedge even where nothing is hidden.
|
||||
const NO_WORKERS_VISIBLE_MESSAGE =
|
||||
'No workers came back. This does NOT establish that no workers are running: an instance can hide workers from callers without the devops role, and it does so by returning an empty list rather than an error. ' +
|
||||
'Tell the user you cannot see any workers and that worker visibility may be restricted for your account, and suggest they check the Workers page themselves. Never state that no workers are online or that the instance has none.'
|
||||
const NO_WORKERS_CONNECTED_MESSAGE =
|
||||
'No workers are connected to this instance (none pinged in the last 5 minutes). Queued runs will stay queued until a worker starts.'
|
||||
const WORKER_PAGE_SIZE = 100
|
||||
|
||||
const deleteWorkspaceItemSchema = z.object({
|
||||
type: itemTypeSchema,
|
||||
path: z.string().describe('Workspace path of the item to delete.'),
|
||||
@@ -1360,7 +1373,7 @@ ${pipelineBullet}
|
||||
? ' By default it preselects the items this chat modified; pass items ("<kind>:<path>" entries) to control the selection'
|
||||
: ' Pass items ("<kind>:<path>" entries naming the items you changed) so the review is scoped to them — omitting items preselects every pending change in the workspace'
|
||||
}, or mode ("draft" or "fork") to force which comparison is shown. Prefer offering this review page over calling deploy_workspace_item directly when several items changed.
|
||||
- For a Windmill operation no other tool covers (workers, queue state, a run's args, ...), use search_api_endpoints to find a REST endpoint, then call_api_get for reads or call_api_endpoint for mutations (the user is asked to confirm those). Always prefer a dedicated tool when one exists; endpoints for authoring or deleting scripts, flows, apps, schedules, resources, or variables are not available through the API catalog tools — use the draft tools and delete_workspace_item instead.
|
||||
- For a Windmill operation no other tool covers (queue state, a run's args, ...), use search_api_endpoints to find a REST endpoint, then call_api_get for reads or call_api_endpoint for mutations (the user is asked to confirm those). Always prefer a dedicated tool when one exists; endpoints for authoring or deleting scripts, flows, apps, schedules, resources, or variables are not available through the API catalog tools — use the draft tools and delete_workspace_item instead.
|
||||
- Default to test_run_script, test_run_flow, or test_run_step for any run request, an existing script included; they prefer drafts and need no deployment. Use run_script or run_flow only when the user names the deployed version ("the deployed X", "in production", "for real") — a bare "run X" is not that. For those two, read the item with read_workspace_item version: "deployed" first so the arguments match the deployed schema. test_run_script, test_run_flow, test_run_step, run_script and run_flow all show the user an argument form prefilled with what you sent, so fill in every argument you can infer rather than asking for it in chat. test_run_step's form is the step's own inputs, not the flow's.
|
||||
- When a required decision is ambiguous, use askUserQuestion with two to ten clear proposed answer strings instead of guessing. The user can also type a custom answer when none of the proposed answers fit. Set multiSelect: true only when the answers can genuinely co-apply and the user may pick several (not mutually exclusive).
|
||||
- When the user asks you to remember a lasting preference, always/never do something, or change/stop a behavior going forward, call update_user_instructions to persist it. It edits only the USER INSTRUCTIONS block (not WORKSPACE INSTRUCTIONS). Keep each instruction concise; do not use it for one-off requests scoped to the current task.
|
||||
@@ -3742,6 +3755,49 @@ export const globalTools: Tool<{}>[] = [
|
||||
return result
|
||||
}
|
||||
},
|
||||
{
|
||||
def: createToolDef(
|
||||
z.object({}),
|
||||
'list_workers',
|
||||
'List the workers connected to this Windmill instance (those that pinged in the last 5 minutes), with their worker group, custom tags, seconds since their last ping, and jobs executed. Pair with list_runs to diagnose a stuck queue: runs queued on a tag no listed worker picks up will never start. Three blind spots to report rather than reason past: an empty result states whether no worker is connected or whether workers may be hidden from you, so relay the one it gives instead of picking; a missing custom_tags can mean tags are hidden from you, not unset; and only the 100 most recently pinging workers are listed, so on a bigger instance a tag none of them carries may still be served.'
|
||||
),
|
||||
planModeSafe: true,
|
||||
showDetails: true,
|
||||
fn: async ({ toolId, toolCallbacks }) => {
|
||||
toolCallbacks.setToolStatus(toolId, { content: 'Listing workers...' })
|
||||
const pings = await WorkerService.listWorkers({ perPage: WORKER_PAGE_SIZE })
|
||||
if (pings.length === 0) {
|
||||
// Both role stores resolve asynchronously, and an unloaded one must not read as
|
||||
// an absent role — that hedges the answer this branch exists to give plainly.
|
||||
// No-ops once they hold a value.
|
||||
await refreshSuperadmin()
|
||||
const hiddenFromCaller = !get(superadmin) && !get(devopsRole)
|
||||
const message = hiddenFromCaller ? NO_WORKERS_VISIBLE_MESSAGE : NO_WORKERS_CONNECTED_MESSAGE
|
||||
toolCallbacks.setToolStatus(toolId, {
|
||||
content: hiddenFromCaller ? 'No workers visible' : 'No workers connected',
|
||||
result: message
|
||||
})
|
||||
return message
|
||||
}
|
||||
const workers = pings.map((w) => ({
|
||||
worker: w.worker,
|
||||
worker_group: w.worker_group,
|
||||
custom_tags: w.custom_tags,
|
||||
last_ping: w.last_ping,
|
||||
jobs_executed: w.jobs_executed
|
||||
}))
|
||||
const note =
|
||||
workers.length === WORKER_PAGE_SIZE
|
||||
? `Only the first ${WORKER_PAGE_SIZE} workers are listed; more may be connected.`
|
||||
: undefined
|
||||
const result = JSON.stringify({ workers, ...(note ? { note } : {}) }, null, 2)
|
||||
toolCallbacks.setToolStatus(toolId, {
|
||||
content: `Listed ${workers.length} worker(s)`,
|
||||
result
|
||||
})
|
||||
return result
|
||||
}
|
||||
},
|
||||
{
|
||||
def: createToolDef(
|
||||
getRunSchema,
|
||||
@@ -4263,7 +4319,7 @@ export const globalTools: Tool<{}>[] = [
|
||||
},
|
||||
// Workspace-scoped datatable tools (unrestricted: no whitelist, no creation policy)
|
||||
...getDatatableTools(),
|
||||
// Workspace DuckLake readiness (storage prerequisite check for pipelines)
|
||||
// Workspace DuckLake: pipeline storage prerequisite, and declared measures
|
||||
...getDucklakeTools(),
|
||||
// Read-only tools over files the user attached to the conversation
|
||||
...fileTools,
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { AI_AGENT_SCHEMA } from './flowInfers'
|
||||
import { AI_AGENT_SCHEMA, memoryOptionLabel, memoryPropertyFor } from './flowInfers'
|
||||
import {
|
||||
AGENT_FIELD_BY_KEY,
|
||||
AGENT_FIELDS,
|
||||
agentMemoryMode,
|
||||
historyInputApplies,
|
||||
agentFieldIsSet,
|
||||
initialVisibleAgentFields
|
||||
} from './agentFormFields'
|
||||
@@ -79,7 +81,69 @@ describe('initialVisibleAgentFields', () => {
|
||||
})
|
||||
|
||||
it('covers every schema key, so no field can only be reached through the raw doc', () => {
|
||||
const registered = new Set(AGENT_FIELDS.map((f) => f.key))
|
||||
const registered = new Set<string>(AGENT_FIELDS.map((f) => f.key))
|
||||
expect(Object.keys(schemaProperties).filter((k) => !registered.has(k))).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('historyInputApplies', () => {
|
||||
// Mirrors the worker: offering a step input a run would ignore misleads the author.
|
||||
it('offers each history input in its own memory mode, and neither on an older setting', () => {
|
||||
expect(agentMemoryMode(undefined)).toBe('off')
|
||||
expect(agentMemoryMode({ kind: 'window', context_length: 0 })).toBe('off')
|
||||
expect(agentMemoryMode({ kind: 'window', context_length: 10 })).toBe('managed')
|
||||
expect(agentMemoryMode({ kind: 'manual', messages: [] })).toBe('legacy')
|
||||
expect(agentMemoryMode({ kind: 'auto', context_length: 4, memory_id: 'x' })).toBe('legacy')
|
||||
expect(agentMemoryMode({ kind: 'auto' })).toBe('off')
|
||||
expect(historyInputApplies('memory_id', 'managed')).toBe(true)
|
||||
expect(historyInputApplies('previous_messages', 'managed')).toBe(false)
|
||||
expect(historyInputApplies('memory_id', 'off')).toBe(false)
|
||||
expect(historyInputApplies('previous_messages', 'off')).toBe(true)
|
||||
expect(historyInputApplies('memory_id', 'legacy')).toBe(false)
|
||||
expect(historyInputApplies('previous_messages', 'legacy')).toBe(false)
|
||||
expect(historyInputApplies('previous_messages', undefined)).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('memoryOptionLabel', () => {
|
||||
// The ignored-input note names the setting by the same label its own button carries.
|
||||
it('names each memory option the way the field renders it', () => {
|
||||
expect(memoryOptionLabel({ kind: 'manual', messages: [] })).toBe('Previous messages (legacy)')
|
||||
expect(memoryOptionLabel({ kind: 'auto', context_length: 4 })).toBe('On (legacy)')
|
||||
expect(memoryOptionLabel({ kind: 'window', context_length: 10 })).toBe('On')
|
||||
// Keeping no messages runs as off, whichever kind says so.
|
||||
expect(memoryOptionLabel({ kind: 'window', context_length: 0 })).toBe('Off')
|
||||
expect(memoryOptionLabel({ kind: 'auto' })).toBe('Off')
|
||||
expect(memoryOptionLabel(undefined)).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('memoryPropertyFor', () => {
|
||||
const property = schemaProperties.memory
|
||||
const kinds = (value: unknown) =>
|
||||
memoryPropertyFor(property, value).oneOf.map((variant: { title: string }) => variant.title)
|
||||
|
||||
it('adds a legacy kind as an option only while the value holds it', () => {
|
||||
expect(memoryPropertyFor(property, { kind: 'window', context_length: 10 })).toBe(property)
|
||||
expect(memoryPropertyFor(property, undefined)).toBe(property)
|
||||
expect(kinds({ kind: 'auto', context_length: 4, memory_id: 'x' })).toEqual([
|
||||
'off',
|
||||
'window',
|
||||
'auto'
|
||||
])
|
||||
expect(kinds({ kind: 'manual', messages: [] })).toEqual(['off', 'window', 'manual'])
|
||||
const autoVariant = (value: unknown) => memoryPropertyFor(property, value).oneOf.at(-1)
|
||||
expect(autoVariant({ kind: 'auto', context_length: 4 }).properties.memory_id).toBeUndefined()
|
||||
expect(
|
||||
autoVariant({ kind: 'auto', context_length: 4, memory_id: 'x' }).properties.memory_id
|
||||
).toBeDefined()
|
||||
// A chat flow drops the baked id on save, so the form does not offer it there.
|
||||
expect(
|
||||
memoryPropertyFor(
|
||||
property,
|
||||
{ kind: 'auto', context_length: 4, memory_id: 'x' },
|
||||
true
|
||||
).oneOf.at(-1).properties.memory_id
|
||||
).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { deepEqual } from 'fast-equals'
|
||||
import type { InputTransform } from '$lib/gen'
|
||||
import type { InputTransform, MemoryConfig } from '$lib/gen'
|
||||
|
||||
/**
|
||||
* How the AI agent form presents `AI_AGENT_SCHEMA`: which group a field belongs to, what it is
|
||||
@@ -25,6 +25,54 @@ export const AGENT_FIELD_GROUPS: { id: AgentFieldGroup; label: string }[] = [
|
||||
* It lives in the registry so the groups keep a single ordering. */
|
||||
export const AGENT_TOOLS_ROW = 'tools'
|
||||
|
||||
/** A step's own history inputs. Never seeded with a placeholder: a run reads a present key as the
|
||||
* step's choice, so only the author adds them. */
|
||||
export const AGENT_HISTORY_KEYS = ['memory_id', 'previous_messages'] as const
|
||||
export type AgentHistoryKey = (typeof AGENT_HISTORY_KEYS)[number]
|
||||
|
||||
/** What turning managed memory on writes. */
|
||||
export const DEFAULT_AGENT_MEMORY: MemoryConfig = { kind: 'window', context_length: 10 }
|
||||
|
||||
/** The docs section on how an agent's memory is named and kept. */
|
||||
export const AGENT_MEMORY_DOCS_URL =
|
||||
'https://www.windmill.dev/docs/core_concepts/ai_agents#memory-auto--manual'
|
||||
|
||||
/** Whether Windmill stores and replays the agent's conversation, mirroring the worker: `window`, or
|
||||
* its older spelling `auto`, with a message count above 0. A legacy `manual` list is not managed. */
|
||||
export function keepsManagedMemory(memory: any): boolean {
|
||||
return (memory?.kind === 'window' || memory?.kind === 'auto') && Boolean(memory.context_length)
|
||||
}
|
||||
|
||||
export type AgentMemoryMode = 'legacy' | 'managed' | 'off'
|
||||
|
||||
/** Which shape a run reads this memory as: an older `auto`/`manual` setting, or the current one. */
|
||||
export function agentMemoryMode(memory: any): AgentMemoryMode {
|
||||
if (memory?.kind === 'manual') return 'legacy'
|
||||
// The worker reads an `auto` that keeps no messages as off, history inputs included, so the form
|
||||
// offers what that run would read.
|
||||
if (memory?.kind === 'auto') return memory.context_length ? 'legacy' : 'off'
|
||||
return keepsManagedMemory(memory) ? 'managed' : 'off'
|
||||
}
|
||||
|
||||
/** Whether a run reads this step input, mirroring the worker: managed memory reads only a memory
|
||||
* id, memory that is off only previous messages, and an older setting neither. A setting the form
|
||||
* cannot read yet leaves both open. */
|
||||
export function historyInputApplies(
|
||||
key: AgentHistoryKey,
|
||||
mode: AgentMemoryMode | undefined
|
||||
): boolean {
|
||||
if (mode === undefined) return true
|
||||
if (mode === 'legacy') return false
|
||||
return (key === 'memory_id') === (mode === 'managed')
|
||||
}
|
||||
|
||||
/** A memory setting in words, for a linked agent's summary. */
|
||||
export function describeMemoryPolicy(memory: any): string {
|
||||
if (keepsManagedMemory(memory)) return `Last ${memory.context_length} messages`
|
||||
if (memory?.kind === 'manual') return 'Off, sends previous messages saved with the agent'
|
||||
return 'Off'
|
||||
}
|
||||
|
||||
export interface AgentFieldSpec {
|
||||
key: string
|
||||
group: AgentFieldGroup
|
||||
@@ -76,6 +124,14 @@ export const AGENT_FIELDS: AgentFieldSpec[] = [
|
||||
tooltip: 'The most tokens the model may produce in its answer.',
|
||||
defaultHint: 'Default: the provider decides'
|
||||
},
|
||||
{
|
||||
key: 'user_message',
|
||||
group: 'messages',
|
||||
label: 'User message',
|
||||
tooltip:
|
||||
"The user turn, sent after the system message and any history. Turn on chat input on the flow's input interface to feed it from the chat.",
|
||||
core: true
|
||||
},
|
||||
{
|
||||
key: 'system_prompt',
|
||||
group: 'messages',
|
||||
@@ -86,20 +142,29 @@ export const AGENT_FIELDS: AgentFieldSpec[] = [
|
||||
{
|
||||
key: 'memory',
|
||||
group: 'messages',
|
||||
label: 'Memory',
|
||||
tooltip:
|
||||
'History sent between the system message and the user message. Windmill can keep it for you, or you can supply the messages yourself.',
|
||||
label: 'Managed memory',
|
||||
tooltip: 'Windmill stores the conversation and sends its last messages with each request.',
|
||||
implicit: { kind: 'off' },
|
||||
defaultHint: 'Default: off',
|
||||
textOnly: true
|
||||
},
|
||||
{
|
||||
key: 'user_message',
|
||||
key: 'memory_id',
|
||||
group: 'messages',
|
||||
label: 'User message',
|
||||
label: 'Memory id',
|
||||
tooltip:
|
||||
"The user turn, sent after the system message and any history. Turn on chat input on the flow's input interface to feed it from the chat.",
|
||||
core: true
|
||||
'Conversation history id: runs with the same id share their history. Inherited uses the memory_id the run was started with: the conversation id in chat mode, or the memory_id query parameter otherwise. Without either, each run starts fresh. Custom sets the id on the step: a fixed id shares one history across all runs, an expression keeps one history per value.',
|
||||
implicit: '',
|
||||
textOnly: true
|
||||
},
|
||||
{
|
||||
key: 'previous_messages',
|
||||
group: 'messages',
|
||||
label: 'Previous messages',
|
||||
tooltip: 'History the flow supplies, sent between the system message and the user message.',
|
||||
implicit: [],
|
||||
defaultHint: 'Default: none',
|
||||
textOnly: true
|
||||
},
|
||||
{
|
||||
key: 'user_attachments',
|
||||
|
||||
@@ -77,7 +77,7 @@ describe('summarizeAgentBrain', () => {
|
||||
output_schema: { type: 'object' } as any
|
||||
})
|
||||
expect(rows).toEqual([
|
||||
{ label: 'Memory', value: 'auto' },
|
||||
{ label: 'Managed memory', value: 'Last 20 messages' },
|
||||
{ label: 'Output schema', value: 'configured' }
|
||||
])
|
||||
})
|
||||
@@ -147,8 +147,11 @@ describe('flowLocalInputs', () => {
|
||||
expect(
|
||||
flowLocalInputs({
|
||||
provider: { type: 'static', value: {} },
|
||||
memory: { type: 'static', value: { kind: 'window', context_length: 10 } },
|
||||
user_message: { type: 'static', value: 'hi' },
|
||||
user_attachments: { type: 'static', value: [] },
|
||||
memory_id: { type: 'javascript', expr: 'flow_input.customer_id' },
|
||||
previous_messages: { type: 'static', value: [{ role: 'user', content: 'earlier' }] },
|
||||
// The roster it narrows belongs to the agent, but which of it one flow may call does
|
||||
// not: saving this into the resource would impose it on every flow linking the agent.
|
||||
enabled_tools: { type: 'javascript', expr: 'flow_input.tools' }
|
||||
@@ -156,6 +159,8 @@ describe('flowLocalInputs', () => {
|
||||
).toEqual({
|
||||
user_message: { type: 'static', value: 'hi' },
|
||||
user_attachments: { type: 'static', value: [] },
|
||||
memory_id: { type: 'javascript', expr: 'flow_input.customer_id' },
|
||||
previous_messages: { type: 'static', value: [{ role: 'user', content: 'earlier' }] },
|
||||
enabled_tools: { type: 'javascript', expr: 'flow_input.tools' }
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { deepEqual } from 'fast-equals'
|
||||
import type { InputTransform } from '$lib/gen'
|
||||
import { AGENT_FIELDS } from './agentFormFields'
|
||||
import { AGENT_FIELDS, describeMemoryPolicy } from './agentFormFields'
|
||||
|
||||
// The brain fields stored flat in an `ai_agent` resource value. The flow-local inputs below are
|
||||
// intentionally excluded — they are supplied per-flow.
|
||||
@@ -20,9 +20,16 @@ export const AGENT_BRAIN_KEYS = [
|
||||
* The inputs a step supplies for itself, whether or not it is linked to a saved agent.
|
||||
*
|
||||
* `enabled_tools` is one of them because it narrows one use of an agent rather than the agent:
|
||||
* saving it into the resource would impose one flow's roster on every flow linking it.
|
||||
* saving it into the resource would impose one flow's roster on every flow linking it. The history
|
||||
* inputs are too, since which conversation a step reads belongs to the flow using the agent.
|
||||
*/
|
||||
export const AGENT_FLOW_LOCAL_KEYS = ['user_message', 'user_attachments', 'enabled_tools'] as const
|
||||
export const AGENT_FLOW_LOCAL_KEYS = [
|
||||
'user_message',
|
||||
'user_attachments',
|
||||
'enabled_tools',
|
||||
'memory_id',
|
||||
'previous_messages'
|
||||
] as const
|
||||
|
||||
export type AgentTool = Record<string, any>
|
||||
|
||||
@@ -177,8 +184,7 @@ export function summarizeAgentBrain(
|
||||
if (key === 'provider') {
|
||||
value = [v.kind, v.model].filter(Boolean).join(' · ') || 'configured'
|
||||
} else if (key === 'memory') {
|
||||
// Memory configs are serialized with a `kind` tag (serde tag = "kind").
|
||||
value = typeof v === 'object' ? (v.kind ?? v.type ?? 'configured') : String(v)
|
||||
value = typeof v === 'object' ? describeMemoryPolicy(v) : String(v)
|
||||
} else if (key === 'output_schema') {
|
||||
value = 'configured'
|
||||
} else if (typeof v === 'boolean') {
|
||||
|
||||
@@ -59,20 +59,26 @@ describe('findAgentToolOwner', () => {
|
||||
})
|
||||
|
||||
it('finds a nested tool owner inside a nested ai agent tool', () => {
|
||||
const nestedAgent = makeAiAgent('support_agent', [makeFlowModuleTool(makeRawModule('create_ticket'))])
|
||||
const nestedAgent = makeAiAgent('support_agent', [
|
||||
makeFlowModuleTool(makeRawModule('create_ticket'))
|
||||
])
|
||||
const rootAgent = makeAiAgent('root_agent', [makeFlowModuleTool(nestedAgent)])
|
||||
|
||||
expect(findAgentToolOwner([rootAgent], 'create_ticket')).toMatchObject({
|
||||
const owner = findAgentToolOwner([rootAgent], 'create_ticket')
|
||||
expect(owner).toMatchObject({
|
||||
agentId: 'support_agent',
|
||||
toolIndex: 0,
|
||||
depth: 2
|
||||
})
|
||||
expect(owner?.agents.map((agent) => agent.id)).toEqual(['root_agent', 'support_agent'])
|
||||
})
|
||||
})
|
||||
|
||||
describe('removeAgentToolOwner', () => {
|
||||
it('removes the matched tool and returns its subtree ids', () => {
|
||||
const nestedAgent = makeAiAgent('support_agent', [makeFlowModuleTool(makeRawModule('create_ticket'))])
|
||||
const nestedAgent = makeAiAgent('support_agent', [
|
||||
makeFlowModuleTool(makeRawModule('create_ticket'))
|
||||
])
|
||||
const rootAgent = makeAiAgent('root_agent', [
|
||||
makeFlowModuleTool(makeRawModule('lookup_user')),
|
||||
makeFlowModuleTool(nestedAgent)
|
||||
@@ -85,7 +91,9 @@ describe('removeAgentToolOwner', () => {
|
||||
removedIds: ['support_agent', 'create_ticket']
|
||||
})
|
||||
expect((rootAgent.value as any).tools).toHaveLength(1)
|
||||
expect(((rootAgent.value as any).tools as any[]).map((tool) => tool.id)).toEqual(['lookup_user'])
|
||||
expect(((rootAgent.value as any).tools as any[]).map((tool) => tool.id)).toEqual([
|
||||
'lookup_user'
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
@@ -93,7 +101,9 @@ describe('collectFlowNodeIds', () => {
|
||||
it('includes ai agent tool ids when deleting an ai agent flow module', () => {
|
||||
const agent = makeAiAgent('root_agent', [
|
||||
makeFlowModuleTool(makeRawModule('lookup_user')),
|
||||
makeFlowModuleTool(makeAiAgent('support_agent', [makeFlowModuleTool(makeRawModule('create_ticket'))]))
|
||||
makeFlowModuleTool(
|
||||
makeAiAgent('support_agent', [makeFlowModuleTool(makeRawModule('create_ticket'))])
|
||||
)
|
||||
])
|
||||
|
||||
expect(collectFlowNodeIds(agent)).toEqual([
|
||||
|
||||
@@ -7,7 +7,7 @@ import {
|
||||
} from './agentToolUtils'
|
||||
import { forEachAiAgentModule } from './aiAgentModules'
|
||||
|
||||
type FlowNodeLike = Pick<FlowModule, 'id' | 'value'>
|
||||
type FlowNodeLike = Pick<FlowModule, 'id' | 'value' | 'summary'>
|
||||
|
||||
export type AgentToolOwner = {
|
||||
agentId: string
|
||||
@@ -15,6 +15,8 @@ export type AgentToolOwner = {
|
||||
toolIndex: number
|
||||
tool: AgentTool
|
||||
depth: number
|
||||
/** Every agent the tool sits under, the step's own first and `agentId`'s last. */
|
||||
agents: FlowNodeLike[]
|
||||
}
|
||||
|
||||
export type RemovedAgentTool = {
|
||||
@@ -26,7 +28,7 @@ export function findAgentToolOwner(
|
||||
modules: FlowModule[],
|
||||
toolId: string
|
||||
): AgentToolOwner | undefined {
|
||||
return findAgentToolOwnerInModules(modules, toolId, 0)
|
||||
return findAgentToolOwnerInModules(modules, toolId, [])
|
||||
}
|
||||
|
||||
export function removeAgentToolOwner(owner: AgentToolOwner): RemovedAgentTool | undefined {
|
||||
@@ -53,10 +55,10 @@ export function collectAgentToolIds(tool: AgentTool): string[] {
|
||||
function findAgentToolOwnerInModules(
|
||||
modules: FlowModule[],
|
||||
toolId: string,
|
||||
depth: number
|
||||
agents: FlowNodeLike[]
|
||||
): AgentToolOwner | undefined {
|
||||
for (const module of modules) {
|
||||
const owner = findAgentToolOwnerInNode(module, toolId, depth)
|
||||
const owner = findAgentToolOwnerInNode(module, toolId, agents)
|
||||
if (owner) {
|
||||
return owner
|
||||
}
|
||||
@@ -68,15 +70,15 @@ function findAgentToolOwnerInModules(
|
||||
function findAgentToolOwnerInNode(
|
||||
node: FlowNodeLike,
|
||||
toolId: string,
|
||||
depth: number
|
||||
agents: FlowNodeLike[]
|
||||
): AgentToolOwner | undefined {
|
||||
if (node.value.type === 'forloopflow' || node.value.type === 'whileloopflow') {
|
||||
return findAgentToolOwnerInModules(node.value.modules, toolId, depth)
|
||||
return findAgentToolOwnerInModules(node.value.modules, toolId, agents)
|
||||
}
|
||||
|
||||
if (node.value.type === 'branchall') {
|
||||
for (const branch of node.value.branches) {
|
||||
const owner = findAgentToolOwnerInModules(branch.modules, toolId, depth)
|
||||
const owner = findAgentToolOwnerInModules(branch.modules, toolId, agents)
|
||||
if (owner) {
|
||||
return owner
|
||||
}
|
||||
@@ -85,12 +87,12 @@ function findAgentToolOwnerInNode(
|
||||
}
|
||||
|
||||
if (node.value.type === 'branchone') {
|
||||
const defaultOwner = findAgentToolOwnerInModules(node.value.default, toolId, depth)
|
||||
const defaultOwner = findAgentToolOwnerInModules(node.value.default, toolId, agents)
|
||||
if (defaultOwner) {
|
||||
return defaultOwner
|
||||
}
|
||||
for (const branch of node.value.branches) {
|
||||
const owner = findAgentToolOwnerInModules(branch.modules, toolId, depth)
|
||||
const owner = findAgentToolOwnerInModules(branch.modules, toolId, agents)
|
||||
if (owner) {
|
||||
return owner
|
||||
}
|
||||
@@ -102,6 +104,7 @@ function findAgentToolOwnerInNode(
|
||||
return undefined
|
||||
}
|
||||
|
||||
const withNode = [...agents, node]
|
||||
// Absent for a linked agent, whose tools live in the resource rather than on the module.
|
||||
const tools = node.value.tools ?? []
|
||||
const toolIndex = tools.findIndex((tool) => tool.id === toolId)
|
||||
@@ -111,7 +114,8 @@ function findAgentToolOwnerInNode(
|
||||
tools,
|
||||
toolIndex,
|
||||
tool: tools[toolIndex],
|
||||
depth: depth + 1
|
||||
depth: withNode.length,
|
||||
agents: withNode
|
||||
}
|
||||
}
|
||||
|
||||
@@ -120,7 +124,7 @@ function findAgentToolOwnerInNode(
|
||||
continue
|
||||
}
|
||||
|
||||
const owner = findAgentToolOwnerInNode(tool as FlowNodeLike, toolId, depth + 1)
|
||||
const owner = findAgentToolOwnerInNode(tool as FlowNodeLike, toolId, withNode)
|
||||
if (owner) {
|
||||
return owner
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { AGENT_HISTORY_KEYS } from './agentFormFields'
|
||||
import type { AiAgent, FlowModule, FlowModuleValue, InputTransform } from '$lib/gen'
|
||||
import { loadStoredConfig } from '../aiProviderStorage'
|
||||
import { AI_AGENT_SCHEMA } from './flowInfers'
|
||||
@@ -138,7 +139,7 @@ export function createAiAgentTool(id: string): AiAgentTool {
|
||||
user_message: { type: 'ai' }
|
||||
}
|
||||
for (const key of Object.keys(AI_AGENT_SCHEMA.properties ?? {})) {
|
||||
if (!(key in input_transforms)) {
|
||||
if (!(key in input_transforms) && !(AGENT_HISTORY_KEYS as readonly string[]).includes(key)) {
|
||||
;(input_transforms as Record<string, InputTransform>)[key] = {
|
||||
type: 'static',
|
||||
value: undefined
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
<script lang="ts">
|
||||
import type { FlowModule } from '$lib/gen'
|
||||
import { getContext } from 'svelte'
|
||||
import { ChevronRight } from 'lucide-svelte'
|
||||
import Button from '$lib/components/common/button/Button.svelte'
|
||||
import type { FlowEditorContext } from '../types'
|
||||
|
||||
interface Props {
|
||||
/** The agents a tool sits under, the step's own first. */
|
||||
agents: Pick<FlowModule, 'id' | 'summary'>[]
|
||||
}
|
||||
|
||||
let { agents }: Props = $props()
|
||||
|
||||
const { selectionManager } = getContext<FlowEditorContext>('FlowEditorContext')
|
||||
</script>
|
||||
|
||||
<nav
|
||||
aria-label="Breadcrumb"
|
||||
class="flex flex-row flex-wrap items-center gap-0.5 min-w-0 text-xs text-secondary"
|
||||
>
|
||||
{#each agents as agent, i (i)}
|
||||
<Button
|
||||
variant="subtle"
|
||||
unifiedSize="2xs"
|
||||
onClick={() => selectionManager.selectId(agent.id, { openPanel: true })}
|
||||
wrapperClasses="min-w-0 shrink"
|
||||
btnClasses="!px-0 !font-normal !text-xs text-secondary hover:text-emphasis hover:underline hover:!bg-transparent min-w-0"
|
||||
>
|
||||
<span class="truncate">{agent.summary || 'AI Agent'}</span>
|
||||
</Button>
|
||||
<ChevronRight size={12} class="text-tertiary shrink-0" />
|
||||
{/each}
|
||||
</nav>
|
||||
@@ -1,5 +1,5 @@
|
||||
<script lang="ts">
|
||||
import type { FlowModuleValue } from '$lib/gen'
|
||||
import type { FlowModule, FlowModuleValue } from '$lib/gen'
|
||||
import FlowCardHeader from './FlowCardHeader.svelte'
|
||||
|
||||
interface Props {
|
||||
@@ -14,6 +14,8 @@
|
||||
header?: import('svelte').Snippet
|
||||
action?: import('svelte').Snippet
|
||||
children?: import('svelte').Snippet
|
||||
/** See `FlowCardHeader`. */
|
||||
agentTrail?: Pick<FlowModule, 'id' | 'summary'>[]
|
||||
isAgentTool?: boolean
|
||||
siblingToolNames?: string[]
|
||||
}
|
||||
@@ -30,6 +32,7 @@
|
||||
header,
|
||||
action,
|
||||
children,
|
||||
agentTrail = undefined,
|
||||
isAgentTool = false,
|
||||
siblingToolNames = undefined
|
||||
}: Props = $props()
|
||||
@@ -49,6 +52,7 @@
|
||||
{subtitleDocLink}
|
||||
{flowModuleValue}
|
||||
{action}
|
||||
{agentTrail}
|
||||
{isAgentTool}
|
||||
{siblingToolNames}
|
||||
>
|
||||
|
||||
@@ -3,7 +3,8 @@
|
||||
import LanguageIcon from '$lib/components/common/languageIcons/LanguageIcon.svelte'
|
||||
import MetadataGen from '$lib/components/copilot/MetadataGen.svelte'
|
||||
import IconedPath from '$lib/components/IconedPath.svelte'
|
||||
import { ScriptService, type FlowModuleValue } from '$lib/gen'
|
||||
import { ScriptService, type FlowModule, type FlowModuleValue } from '$lib/gen'
|
||||
import AgentTrail from './AgentTrail.svelte'
|
||||
import {
|
||||
ArrowUpCircle,
|
||||
Flag,
|
||||
@@ -39,6 +40,10 @@
|
||||
subtitleDocLink?: string | undefined
|
||||
children?: import('svelte').Snippet
|
||||
action?: import('svelte').Snippet
|
||||
/** For an agent tool, the agents it sits under, shown above the header as the way back up:
|
||||
* a nested agent's tools have no graph node to reach them from. Each crumb selects its agent,
|
||||
* so pass it only where selecting an agent opens it (not in the saved-agent editor). */
|
||||
agentTrail?: Pick<FlowModule, 'id' | 'summary'>[]
|
||||
isAgentTool?: boolean
|
||||
siblingToolNames?: string[]
|
||||
}
|
||||
@@ -52,6 +57,7 @@
|
||||
subtitleDocLink = undefined,
|
||||
children,
|
||||
action,
|
||||
agentTrail = undefined,
|
||||
isAgentTool = false,
|
||||
siblingToolNames = undefined
|
||||
}: Props = $props()
|
||||
@@ -192,6 +198,9 @@
|
||||
</script>
|
||||
|
||||
<div class="flex flex-col gap-1 px-4 py-2">
|
||||
{#if agentTrail?.length}
|
||||
<AgentTrail agents={agentTrail} />
|
||||
{/if}
|
||||
<div
|
||||
class="overflow-x-auto scrollbar-hidden flex items-center justify-between flex-nowrap w-full"
|
||||
>
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
<script lang="ts">
|
||||
import { Alert, Button } from '$lib/components/common'
|
||||
import { keepsManagedMemory } from '../agentFormFields'
|
||||
|
||||
interface Props {
|
||||
/** The agent's input transforms. Converting a legacy setting writes `memory` and the step input
|
||||
* it moves into. */
|
||||
args: Record<string, any>
|
||||
chatInputEnabled?: boolean
|
||||
/** Whether the step's own memory id and previous messages are on this form. A saved agent has
|
||||
* neither: they belong to each step linking it. */
|
||||
historyOnStep?: boolean
|
||||
s3StorageConfigured?: boolean
|
||||
}
|
||||
|
||||
let {
|
||||
args = $bindable(),
|
||||
chatInputEnabled = false,
|
||||
historyOnStep = false,
|
||||
s3StorageConfigured = true
|
||||
}: Props = $props()
|
||||
|
||||
let memory = $derived(
|
||||
args?.memory?.type === 'static'
|
||||
? (args.memory.value as Record<string, any> | null | undefined)
|
||||
: undefined
|
||||
)
|
||||
let on = $derived(keepsManagedMemory(memory))
|
||||
// `auto` and `manual` are what older editors wrote. They stay as they are until the author
|
||||
// converts them, so an untouched step still runs on an older worker.
|
||||
let legacyMessages = $derived(
|
||||
memory?.kind === 'manual' ? ((memory.messages ?? []) as unknown[]) : undefined
|
||||
)
|
||||
// A chat run always carries the conversation's memory id, so there a baked id was never read.
|
||||
let legacyMemoryId = $derived(
|
||||
on && memory?.kind === 'auto' && memory.memory_id && !chatInputEnabled
|
||||
? String(memory.memory_id)
|
||||
: undefined
|
||||
)
|
||||
|
||||
// An `auto` setting whose saved id is never read runs exactly like the current setting for its
|
||||
// state, so switching to that setting is the only choice.
|
||||
let legacyEquivalent = $derived(memory?.kind === 'auto' && !legacyMemoryId)
|
||||
|
||||
// The older setting never read the step's own memory id, so a conversion that promises the same
|
||||
// behaviour, or the run's id, drops it rather than bringing it to life. Off keeps ignoring it.
|
||||
function switchToEquivalent() {
|
||||
if (on) delete args.memory_id
|
||||
args.memory = {
|
||||
type: 'static',
|
||||
value: on ? { kind: 'window', context_length: memory?.context_length } : { kind: 'off' }
|
||||
}
|
||||
}
|
||||
|
||||
function convertLegacyMemoryId(keepAsMemoryId: boolean) {
|
||||
if (keepAsMemoryId && legacyMemoryId) {
|
||||
args.memory_id = { type: 'static', value: legacyMemoryId }
|
||||
} else {
|
||||
delete args.memory_id
|
||||
}
|
||||
args.memory = {
|
||||
type: 'static',
|
||||
value: { kind: 'window', context_length: memory?.context_length }
|
||||
}
|
||||
}
|
||||
|
||||
function moveMessagesToStep() {
|
||||
args.previous_messages = { type: 'static', value: $state.snapshot(legacyMessages) ?? [] }
|
||||
args.memory = { type: 'static', value: { kind: 'off' } }
|
||||
}
|
||||
</script>
|
||||
|
||||
{#if on && !s3StorageConfigured}
|
||||
<p class="mt-1 text-2xs text-hint">
|
||||
Without S3 storage on the workspace, memory is kept in the database, up to 100KB per memory.
|
||||
</p>
|
||||
{/if}
|
||||
{#if legacyMessages}
|
||||
<Alert type="info" title="Older memory setting" class="mt-2">
|
||||
<div class="flex flex-col gap-2">
|
||||
<span>
|
||||
An earlier version of the editor saved these previous messages inside the memory setting,
|
||||
and this agent still sends them.
|
||||
</span>
|
||||
{#if historyOnStep}
|
||||
<div class="flex">
|
||||
<Button
|
||||
variant="default"
|
||||
unifiedSize="sm"
|
||||
btnClasses="bg-surface"
|
||||
onclick={moveMessagesToStep}
|
||||
>
|
||||
Move to previous messages
|
||||
</Button>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
</Alert>
|
||||
{/if}
|
||||
{#if legacyMemoryId}
|
||||
<Alert type="info" title="Older memory setting" class="mt-2">
|
||||
<div class="flex flex-col gap-2">
|
||||
<span>
|
||||
{historyOnStep
|
||||
? 'Fixed memory id generated when this flow was saved.'
|
||||
: 'Fixed memory id saved with this agent.'}
|
||||
Every run shares it unless the caller passes one.
|
||||
</span>
|
||||
<div class="flex gap-2">
|
||||
{#if historyOnStep}
|
||||
<Button
|
||||
variant="default"
|
||||
unifiedSize="sm"
|
||||
btnClasses="bg-surface"
|
||||
onclick={() => convertLegacyMemoryId(true)}
|
||||
>
|
||||
Keep as memory id
|
||||
</Button>
|
||||
{/if}
|
||||
<Button
|
||||
variant="default"
|
||||
unifiedSize="sm"
|
||||
btnClasses="bg-surface"
|
||||
onclick={() => convertLegacyMemoryId(false)}
|
||||
>
|
||||
Use the run's memory id
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</Alert>
|
||||
{/if}
|
||||
{#if legacyEquivalent}
|
||||
<Alert type="info" title="Older memory setting" class="mt-2">
|
||||
<div class="flex flex-col gap-2">
|
||||
<span>
|
||||
An earlier version of the editor saved this setting. It works the same as {on
|
||||
? 'On'
|
||||
: 'Off'}.
|
||||
</span>
|
||||
<div class="flex">
|
||||
<Button
|
||||
variant="default"
|
||||
unifiedSize="sm"
|
||||
btnClasses="bg-surface"
|
||||
onclick={switchToEquivalent}
|
||||
>
|
||||
Switch to {on ? 'On' : 'Off'}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</Alert>
|
||||
{/if}
|
||||
@@ -53,7 +53,9 @@
|
||||
moduleId,
|
||||
opWorkspace = undefined,
|
||||
flowPath = '',
|
||||
fromAgentEditor = false
|
||||
fromAgentEditor = false,
|
||||
chatInputEnabled = false,
|
||||
linkedMemory = $bindable()
|
||||
}: {
|
||||
agent: string | undefined
|
||||
inputTransforms: Record<string, InputTransform>
|
||||
@@ -71,6 +73,9 @@
|
||||
// backend supports it, but only a flow can author it, and a second editor over a second draft
|
||||
// is the wrong way in.
|
||||
fromAgentEditor?: boolean
|
||||
chatInputEnabled?: boolean
|
||||
// The linked agent's memory once its config has loaded, for the step's history inputs.
|
||||
linkedMemory?: { memory: unknown } | undefined
|
||||
} = $props()
|
||||
|
||||
let ws = $derived(opWorkspace ?? $workspaceStore)
|
||||
@@ -211,6 +216,9 @@
|
||||
let linkedInfo = $derived(
|
||||
loadedInfo?.ws === ws && loadedInfo?.path === agent ? loadedInfo : undefined
|
||||
)
|
||||
$effect(() => {
|
||||
linkedMemory = linkedInfo ? { memory: linkedInfo.config?.memory } : undefined
|
||||
})
|
||||
let inheritedTools = $derived(linkedInfo?.tools ?? [])
|
||||
let brainParams = $derived(summarizeAgentBrain(linkedInfo?.config))
|
||||
let providerPath = $derived(linkedInfo?.providerPath)
|
||||
@@ -312,6 +320,20 @@
|
||||
// saved without a complete one fails on every linked run. Block saving when the provider is
|
||||
// computed/connected (only a static value can be captured into the resource) or when the static
|
||||
// value is incomplete (a fresh step defaults to empty resource/model, which is still static).
|
||||
// A saved agent never carries a memory id, so saving would drop the id this step's runs still fall
|
||||
// back to and leave them without memory. The author picks what replaces it first. In chat mode the
|
||||
// conversation id always won, so there the id was never read.
|
||||
let legacyMemorySaveError = $derived.by(() => {
|
||||
const memory = inputTransforms?.memory as
|
||||
| { type?: string; value?: { kind?: string; context_length?: number; memory_id?: string } }
|
||||
| undefined
|
||||
const value = memory?.type === 'static' ? memory.value : undefined
|
||||
if (chatInputEnabled || value?.kind !== 'auto' || !value.memory_id || !value.context_length) {
|
||||
return undefined
|
||||
}
|
||||
return "This step still uses a fixed memory id from an earlier version. In Managed memory, choose Keep as memory id or Use the run's memory id, then save it as an agent."
|
||||
})
|
||||
|
||||
let providerSaveError = $derived.by(() => {
|
||||
const t = inputTransforms?.provider as
|
||||
| { type?: string; value?: { resource?: string; model?: string } }
|
||||
@@ -343,8 +365,8 @@
|
||||
// the success toast that would otherwise bury the explanation.
|
||||
async function persist(path: string, description?: string): Promise<boolean> {
|
||||
const dropped = nonStaticBrainKeys(inputTransforms)
|
||||
if (providerSaveError) {
|
||||
throw new Error(providerSaveError)
|
||||
if (providerSaveError ?? legacyMemorySaveError) {
|
||||
throw new Error(providerSaveError ?? legacyMemorySaveError)
|
||||
}
|
||||
if (dropped.length > 0) {
|
||||
sendUserToast(
|
||||
@@ -355,6 +377,12 @@
|
||||
// Tool inputs are saved verbatim: the agent carries its tools' default bindings (static, AI or
|
||||
// flow expressions) as authored. Host flows override per-step via tool_inputs, never here.
|
||||
const value = inputTransformsToAgentConfig(inputTransforms, tools)
|
||||
// An id an older editor baked into this step names the flow's memory. The agent is shared by
|
||||
// every step linking it, and each of those takes its memory id from its own run.
|
||||
if (value.memory && typeof value.memory === 'object' && 'memory_id' in value.memory) {
|
||||
const { memory_id: _, ...memory } = value.memory as Record<string, unknown>
|
||||
value.memory = memory
|
||||
}
|
||||
// The editor stays live during the requests below, so remember what linking would discard:
|
||||
// every brain transform and the tools. Comparing the saved config instead would miss a
|
||||
// non-static brain edit, which the resource cannot hold yet linking still strips.
|
||||
@@ -691,9 +719,9 @@
|
||||
size="sm"
|
||||
/>
|
||||
</label>
|
||||
{#if providerSaveError}
|
||||
{#if providerSaveError ?? legacyMemorySaveError}
|
||||
<p class="text-xs text-red-600 dark:text-red-400">
|
||||
{providerSaveError}
|
||||
{providerSaveError ?? legacyMemorySaveError}
|
||||
</p>
|
||||
{/if}
|
||||
</div>
|
||||
@@ -701,7 +729,10 @@
|
||||
<Button
|
||||
variant="accent"
|
||||
startIcon={{ icon: Save }}
|
||||
disabled={!newPath || !!pathError || saving || !!providerSaveError}
|
||||
disabled={!newPath ||
|
||||
!!pathError ||
|
||||
saving ||
|
||||
!!(providerSaveError ?? legacyMemorySaveError)}
|
||||
onclick={saveAsAgent}
|
||||
>
|
||||
Save agent
|
||||
|
||||
@@ -20,6 +20,8 @@
|
||||
emptyMessage?: string
|
||||
/** Where the picker's popover belongs, when the roster is not inside the flow editor. */
|
||||
pickerPortal?: string
|
||||
/** See `InsertModuleInner`. */
|
||||
allowAiAgentTool?: boolean
|
||||
}
|
||||
|
||||
let {
|
||||
@@ -28,7 +30,8 @@
|
||||
onAddTool = undefined,
|
||||
onDeleteTool = undefined,
|
||||
emptyMessage = 'No tools yet. Add one from the agent on the flow graph.',
|
||||
pickerPortal = '#flow-editor'
|
||||
pickerPortal = '#flow-editor',
|
||||
allowAiAgentTool = true
|
||||
}: Props = $props()
|
||||
|
||||
let funcDesc = $state('')
|
||||
@@ -81,6 +84,7 @@
|
||||
<InsertModuleInner
|
||||
bind:funcDesc
|
||||
toolMode
|
||||
{allowAiAgentTool}
|
||||
on:close={close}
|
||||
on:new={(e) => (onAddTool?.(e.detail), close())}
|
||||
on:insert={(e) => (onAddTool?.(e.detail), close())}
|
||||
|
||||
@@ -20,6 +20,9 @@
|
||||
staticOnly?: boolean
|
||||
/** See `FlowModuleComponent`: set where there is no graph to select a nested tool on. */
|
||||
noToolNavigation?: boolean
|
||||
/** See `FlowCardHeader`. */
|
||||
agentTrail?: Pick<FlowModule, 'id' | 'summary'>[]
|
||||
flowModuleSchemaMap?: import('../map/FlowModuleSchemaMap.svelte').default
|
||||
}
|
||||
|
||||
let {
|
||||
@@ -32,7 +35,9 @@
|
||||
highlightArg,
|
||||
siblingToolNames = undefined,
|
||||
staticOnly = false,
|
||||
noToolNavigation = false
|
||||
noToolNavigation = false,
|
||||
agentTrail = undefined,
|
||||
flowModuleSchemaMap = undefined
|
||||
}: Props = $props()
|
||||
</script>
|
||||
|
||||
@@ -65,12 +70,14 @@
|
||||
isAgentTool={true}
|
||||
{staticOnly}
|
||||
{noToolNavigation}
|
||||
{agentTrail}
|
||||
{flowModuleSchemaMap}
|
||||
bind:toolDescription={tool.description}
|
||||
{siblingToolNames}
|
||||
/>
|
||||
{:else if isMcpTool(tool)}
|
||||
<!-- MCP tool - use McpToolEditor -->
|
||||
<McpToolEditor bind:tool {noEditor} />
|
||||
<McpToolEditor bind:tool {noEditor} {agentTrail} />
|
||||
{:else if isWebsearchTool(tool)}
|
||||
<WebsearchToolDisplay {noEditor} />
|
||||
<WebsearchToolDisplay {noEditor} {agentTrail} />
|
||||
{/if}
|
||||
|
||||
@@ -32,7 +32,7 @@
|
||||
import { type InputTransform } from '$lib/gen'
|
||||
import { workspaceStore } from '$lib/stores'
|
||||
import { allTrue, type DynamicInput as DynamicInputTypes } from '$lib/utils'
|
||||
import { getContext, untrack } from 'svelte'
|
||||
import { getContext, untrack, type Snippet } from 'svelte'
|
||||
import { SvelteSet } from 'svelte/reactivity'
|
||||
import { Button } from '$lib/components/common'
|
||||
import StepInputsGen from '$lib/components/copilot/StepInputsGen.svelte'
|
||||
@@ -43,19 +43,32 @@
|
||||
import type VariableEditor from '$lib/components/VariableEditor.svelte'
|
||||
import DropdownV2 from '$lib/components/DropdownV2.svelte'
|
||||
import ResizeTransitionWrapper from '$lib/components/common/ResizeTransitionWrapper.svelte'
|
||||
import FieldHeader from '$lib/components/FieldHeader.svelte'
|
||||
import ToggleButton from '$lib/components/common/toggleButton-v2/ToggleButton.svelte'
|
||||
import ToggleButtonGroup from '$lib/components/common/toggleButton-v2/ToggleButtonGroup.svelte'
|
||||
import { AlertTriangle, Plus, X } from 'lucide-svelte'
|
||||
import type { PickableProperties } from '../previousResults'
|
||||
import type { FlowCopilotContext } from '$lib/components/copilot/flow'
|
||||
import { toolEnabledName, type AgentTool } from '../agentToolUtils'
|
||||
import {
|
||||
AGENT_FIELDS,
|
||||
AGENT_FIELD_BY_KEY,
|
||||
AGENT_HISTORY_KEYS,
|
||||
AGENT_MEMORY_DOCS_URL,
|
||||
AGENT_TOOLS_ROW,
|
||||
AGENT_FIELD_GROUPS,
|
||||
agentFieldAppliesTo,
|
||||
agentMemoryMode,
|
||||
historyInputApplies,
|
||||
type AgentMemoryMode,
|
||||
initialVisibleAgentFields,
|
||||
type AgentFieldGroup,
|
||||
type AgentFieldSpec
|
||||
type AgentFieldSpec,
|
||||
type AgentHistoryKey
|
||||
} from '../agentFormFields'
|
||||
import AgentToolRoster from './AgentToolRoster.svelte'
|
||||
import AgentMemoryNotes from './AgentMemoryNotes.svelte'
|
||||
import { memoryOptionLabel, memoryPropertyFor } from '../flowInfers'
|
||||
|
||||
interface Props {
|
||||
schema: Schema | { properties?: Record<string, any> }
|
||||
@@ -99,6 +112,9 @@
|
||||
onDeleteTool?: (toolId: string) => void
|
||||
/** Where the tool picker's popover belongs, for a surface that is not the flow editor. */
|
||||
toolPickerPortal?: string
|
||||
/** A linked agent's memory, once its config has loaded: whether it keeps managed memory decides
|
||||
* which history inputs the step offers. */
|
||||
linkedMemory?: { memory: unknown } | undefined
|
||||
}
|
||||
|
||||
let {
|
||||
@@ -128,7 +144,8 @@
|
||||
onSelectTool = undefined,
|
||||
onAddTool = undefined,
|
||||
onDeleteTool = undefined,
|
||||
toolPickerPortal = undefined
|
||||
toolPickerPortal = undefined,
|
||||
linkedMemory = undefined
|
||||
}: Props = $props()
|
||||
|
||||
let ws = $derived(workspace ?? $workspaceStore)
|
||||
@@ -163,6 +180,32 @@
|
||||
|
||||
let schemaProperties = $derived((schema?.properties ?? {}) as Record<string, any>)
|
||||
|
||||
// Which memory shape the brain edited here, or the linked agent's, holds. Unknown for an
|
||||
// expression or a linked agent that has not loaded, which keeps previous messages addable.
|
||||
let memoryMode = $derived.by((): AgentMemoryMode | undefined => {
|
||||
if ('memory' in schemaProperties) {
|
||||
const transform = args?.memory
|
||||
return transform == undefined || transform.type === 'static'
|
||||
? agentMemoryMode(transform?.value)
|
||||
: undefined
|
||||
}
|
||||
return linkedMemory ? agentMemoryMode(linkedMemory.memory) : undefined
|
||||
})
|
||||
|
||||
// The one-of field rewrites a value that matches none of its options, so a legacy kind the step
|
||||
// still holds is offered alongside the current ones.
|
||||
let memoryFieldSchema = $derived.by(() => {
|
||||
const property = schemaProperties.memory
|
||||
const value = args?.memory?.type === 'static' ? args.memory.value : undefined
|
||||
const withLegacy = memoryPropertyFor(property, value, chatInputEnabled)
|
||||
if (withLegacy === property) return schema
|
||||
return { ...schema, properties: { ...schemaProperties, memory: withLegacy } }
|
||||
})
|
||||
|
||||
function isHistoryKey(key: string): key is AgentHistoryKey {
|
||||
return (AGENT_HISTORY_KEYS as readonly string[]).includes(key)
|
||||
}
|
||||
|
||||
// Offer the agent's own tools as the choices for `enabled_tools`, rather than asking for names
|
||||
// to be typed. Written into the schema because that is where `InputTransformForm` reads a
|
||||
// field's shape from; `flowInfers` hands every step its own copy, so this stays this step's.
|
||||
@@ -190,6 +233,54 @@
|
||||
)
|
||||
)
|
||||
|
||||
// Offered when managed memory is on or an expression the form cannot read, not while a linked
|
||||
// agent's setting is unknown.
|
||||
// Unset, the memory id the run was started with applies, so the step's own id sits behind a
|
||||
// choice and the key exists only once Custom is picked.
|
||||
let memoryIsExpression = $derived(
|
||||
'memory' in schemaProperties &&
|
||||
(args?.memory?.type === 'javascript' || args?.memory?.type === 'ai')
|
||||
)
|
||||
// Names the legacy value the way the memory field's own button does, reading it wherever the mode
|
||||
// came from, so the row and the setting it points at cannot name it differently.
|
||||
let legacyMemoryNote = $derived.by(() => {
|
||||
const onThisForm = 'memory' in schemaProperties
|
||||
const label = memoryOptionLabel(
|
||||
onThisForm
|
||||
? args?.memory?.type === 'static'
|
||||
? args.memory.value
|
||||
: undefined
|
||||
: linkedMemory?.memory
|
||||
)
|
||||
return onThisForm
|
||||
? `Ignored while memory is set to ${label}.`
|
||||
: `Ignored while the agent's memory is set to ${label}.`
|
||||
})
|
||||
|
||||
let memoryIdOffered = $derived(
|
||||
(memoryMode === 'managed' || memoryIsExpression) &&
|
||||
scopedFields.some((spec) => spec.key === 'memory_id')
|
||||
)
|
||||
|
||||
// A history input's row follows its key: the remembered `visible` set can outlive a key that a
|
||||
// save, an undo or the AI chat removed, and a row with no value renders no field.
|
||||
function isShown(key: string): boolean {
|
||||
if (isHistoryKey(key)) {
|
||||
return args?.[key] != undefined || (key === 'memory_id' && memoryIdOffered)
|
||||
}
|
||||
return visible.has(key)
|
||||
}
|
||||
|
||||
function setCustomMemoryId(on: boolean) {
|
||||
if (!args || on === (args.memory_id != undefined)) return
|
||||
if (on) {
|
||||
args.memory_id = { type: 'static', value: '' }
|
||||
} else {
|
||||
delete args.memory_id
|
||||
delete inputCheck.memory_id
|
||||
}
|
||||
}
|
||||
|
||||
let outputType = $derived.by(() => {
|
||||
const transform = args?.['output_type']
|
||||
return transform && transform.type === 'static' ? transform.value : undefined
|
||||
@@ -229,21 +320,32 @@
|
||||
})
|
||||
})
|
||||
|
||||
// A history input's row follows its key rather than `visible`, so the run form is told about one
|
||||
// only while the step holds the key: an inherited memory id has nothing a test run could inherit.
|
||||
$effect(() => {
|
||||
const keys = [...visible]
|
||||
const keys = [
|
||||
...[...visible].filter((key) => !isHistoryKey(key)),
|
||||
...AGENT_HISTORY_KEYS.filter((key) => args?.[key] != undefined)
|
||||
]
|
||||
untrack(() => rememberOpenFields(visibilityKey, keys))
|
||||
})
|
||||
|
||||
function rowsIn(group: AgentFieldGroup): AgentFieldSpec[] {
|
||||
return scopedFields.filter(
|
||||
(spec) => spec.group === group && visible.has(spec.key) && !(imageOutput && spec.textOnly)
|
||||
(spec) => spec.group === group && isShown(spec.key) && !(imageOutput && spec.textOnly)
|
||||
)
|
||||
}
|
||||
|
||||
function addableIn(): AgentFieldSpec[] {
|
||||
return scopedFields.filter(
|
||||
(spec) =>
|
||||
!spec.core && !spec.virtual && !visible.has(spec.key) && !(imageOutput && spec.textOnly)
|
||||
!spec.core &&
|
||||
!spec.virtual &&
|
||||
!isShown(spec.key) &&
|
||||
!(imageOutput && spec.textOnly) &&
|
||||
// Memory id's row appears on its own when it is offered, so the menu never adds it.
|
||||
spec.key !== 'memory_id' &&
|
||||
!(isHistoryKey(spec.key) && !historyInputApplies(spec.key, memoryMode))
|
||||
)
|
||||
}
|
||||
|
||||
@@ -260,10 +362,14 @@
|
||||
function removeField(spec: AgentFieldSpec) {
|
||||
visible.delete(spec.key)
|
||||
if (args) {
|
||||
// Back to exactly what `flowInfers` seeds, so removing a field leaves no diff behind.
|
||||
// Never `delete args[key]`: the key returns on the next load, and the CLI linter requires
|
||||
// `user_message` to be present.
|
||||
args[spec.key] = { type: 'static', value: undefined }
|
||||
if (isHistoryKey(spec.key)) {
|
||||
delete args[spec.key]
|
||||
} else {
|
||||
// Back to exactly what `flowInfers` seeds, so removing a field leaves no diff behind.
|
||||
// Never `delete args[key]`: the key returns on the next load, and the CLI linter requires
|
||||
// `user_message` to be present.
|
||||
args[spec.key] = { type: 'static', value: undefined }
|
||||
}
|
||||
}
|
||||
// InputTransformSchemaForm leaks these on unmount, which would pin `isValid` false forever
|
||||
// once hiding a row is routine.
|
||||
@@ -294,6 +400,92 @@
|
||||
)
|
||||
</script>
|
||||
|
||||
{#snippet unsetButton(spec: AgentFieldSpec)}
|
||||
{#if !spec.core && !readOnly}
|
||||
<Button
|
||||
variant="subtle"
|
||||
unifiedSize="2xs"
|
||||
iconOnly
|
||||
startIcon={{ icon: X }}
|
||||
wrapperClasses="ml-1"
|
||||
title="Unset {spec.label}"
|
||||
on:click={() => removeField(spec)}
|
||||
/>
|
||||
{/if}
|
||||
{/snippet}
|
||||
|
||||
{#snippet memoryIdHeader()}
|
||||
<div class="flex flex-col gap-1">
|
||||
<FieldHeader
|
||||
label={AGENT_FIELD_BY_KEY.memory_id.label}
|
||||
simpleTooltip={AGENT_FIELD_BY_KEY.memory_id.tooltip}
|
||||
displayType={false}
|
||||
/>
|
||||
<ToggleButtonGroup
|
||||
selected={args?.memory_id == undefined ? 'inherited' : 'custom'}
|
||||
onSelected={(next) => setCustomMemoryId(next === 'custom')}
|
||||
>
|
||||
{#snippet children({ item })}
|
||||
<ToggleButton value="inherited" label="Inherited" {item} />
|
||||
<ToggleButton value="custom" label="Custom" {item} />
|
||||
{/snippet}
|
||||
</ToggleButtonGroup>
|
||||
</div>
|
||||
{/snippet}
|
||||
|
||||
{#snippet transformField(
|
||||
key: string,
|
||||
label: string,
|
||||
tooltip: string | undefined,
|
||||
removable: AgentFieldSpec | undefined,
|
||||
header: Snippet | undefined = undefined,
|
||||
collapsed: boolean = false
|
||||
)}
|
||||
<InputTransformForm
|
||||
{previousModuleId}
|
||||
bind:arg={args[key]}
|
||||
bind:schema={
|
||||
() => (key === 'memory' ? memoryFieldSchema : schema),
|
||||
(value) => {
|
||||
if (key !== 'memory') schema = value
|
||||
}
|
||||
}
|
||||
argName={key}
|
||||
{label}
|
||||
headerTooltip={tooltip}
|
||||
hideDescription
|
||||
subtleControls
|
||||
{header}
|
||||
indentUnderHeader={false}
|
||||
{collapsed}
|
||||
animateAppear={header != undefined}
|
||||
argExtra={schemaProperties[key] ?? {}}
|
||||
bind:inputCheck={() => inputCheck[key] ?? false, (value) => (inputCheck[key] = value)}
|
||||
bind:extraLib={() => extraLib ?? 'missing extraLib', (v) => (extraLib = v)}
|
||||
{variableEditor}
|
||||
{itemPicker}
|
||||
bind:pickForField
|
||||
{pickableProperties}
|
||||
enableAi={fieldAiEnabled}
|
||||
{helperScript}
|
||||
{isAgentTool}
|
||||
{allowedAiTransforms}
|
||||
noDynamicToggle={staticOnly}
|
||||
noConnect={staticOnly || noConnect}
|
||||
noJavascript={staticOnly || noJavascript}
|
||||
s3StorageConfigured={s3Storage.current}
|
||||
{chatInputEnabled}
|
||||
{workspace}
|
||||
otherArgs={Object.fromEntries(Object.entries(args ?? {}).filter(([other]) => other !== key))}
|
||||
>
|
||||
{#snippet labelExtra()}
|
||||
{#if removable}
|
||||
{@render unsetButton(removable)}
|
||||
{/if}
|
||||
{/snippet}
|
||||
</InputTransformForm>
|
||||
{/snippet}
|
||||
|
||||
{#snippet addFieldMenu()}
|
||||
{@const candidates = addableIn()}
|
||||
{#if candidates.length > 0}
|
||||
@@ -359,73 +551,66 @@
|
||||
<div class="flex flex-col gap-6">
|
||||
{#each rows as spec (spec.key)}
|
||||
<ResizeTransitionWrapper innerClass="w-full" vertical>
|
||||
{#if spec.virtual}
|
||||
{#if spec.key === AGENT_TOOLS_ROW}
|
||||
<AgentToolRoster
|
||||
{tools}
|
||||
{onSelectTool}
|
||||
{onAddTool}
|
||||
{onDeleteTool}
|
||||
pickerPortal={toolPickerPortal}
|
||||
allowAiAgentTool={!isAgentTool}
|
||||
/>
|
||||
{:else}
|
||||
<!-- Inert rather than merely button-less: every control below writes into
|
||||
`args`, and a read-only viewer's edit is rejected by the server. Dimmed
|
||||
with it, so a field that ignores a click looks like it meant to. -->
|
||||
<div class="w-full {readOnly ? 'opacity-60' : ''}" inert={readOnly}>
|
||||
<InputTransformForm
|
||||
{previousModuleId}
|
||||
bind:arg={args[spec.key]}
|
||||
bind:schema
|
||||
argName={spec.key}
|
||||
label={spec.label}
|
||||
headerTooltip={spec.tooltip}
|
||||
hideDescription
|
||||
subtleControls
|
||||
argExtra={schemaProperties[spec.key] ?? {}}
|
||||
bind:inputCheck={
|
||||
() => inputCheck[spec.key] ?? false,
|
||||
(value) => (inputCheck[spec.key] = value)
|
||||
}
|
||||
bind:extraLib={() => extraLib ?? 'missing extraLib', (v) => (extraLib = v)}
|
||||
{variableEditor}
|
||||
{itemPicker}
|
||||
bind:pickForField
|
||||
{pickableProperties}
|
||||
enableAi={fieldAiEnabled}
|
||||
{helperScript}
|
||||
{isAgentTool}
|
||||
{allowedAiTransforms}
|
||||
noDynamicToggle={staticOnly}
|
||||
noConnect={staticOnly || noConnect}
|
||||
noJavascript={staticOnly || noJavascript}
|
||||
s3StorageConfigured={s3Storage.current}
|
||||
{chatInputEnabled}
|
||||
{workspace}
|
||||
otherArgs={Object.fromEntries(
|
||||
Object.entries(args ?? {}).filter(([key]) => key !== spec.key)
|
||||
{#if spec.key === 'memory'}
|
||||
{@render transformField(spec.key, spec.label, spec.tooltip, spec)}
|
||||
<AgentMemoryNotes
|
||||
bind:args
|
||||
{chatInputEnabled}
|
||||
historyOnStep={scopedFields.some((f) => f.key === 'previous_messages')}
|
||||
s3StorageConfigured={s3Storage.current}
|
||||
/>
|
||||
{:else if spec.key === 'memory_id' && memoryIdOffered}
|
||||
{@render transformField(
|
||||
spec.key,
|
||||
spec.label,
|
||||
spec.tooltip,
|
||||
undefined,
|
||||
memoryIdHeader,
|
||||
args?.memory_id == undefined
|
||||
)}
|
||||
>
|
||||
{#snippet labelExtra()}
|
||||
{#if !spec.core && !readOnly}
|
||||
<Button
|
||||
variant="subtle"
|
||||
unifiedSize="2xs"
|
||||
iconOnly
|
||||
startIcon={{ icon: X }}
|
||||
wrapperClasses="ml-1"
|
||||
title="Unset {spec.label}"
|
||||
on:click={() => removeField(spec)}
|
||||
/>
|
||||
{/if}
|
||||
{/snippet}
|
||||
</InputTransformForm>
|
||||
{#if spec.key === 'enabled_tools' && noToolsEnabled}
|
||||
<div
|
||||
class="mt-1 flex items-center gap-1 text-2xs text-yellow-600 dark:text-yellow-400"
|
||||
>
|
||||
<AlertTriangle size={12} />
|
||||
Nothing selected: the agent runs with no tools.
|
||||
</div>
|
||||
{#if args?.memory_id == undefined}
|
||||
<p class="mt-1 text-xs text-secondary">
|
||||
Uses the <code>memory_id</code> the run was started with: the conversation
|
||||
id in chat mode, or the <code>memory_id</code> query parameter otherwise.
|
||||
<a
|
||||
href={AGENT_MEMORY_DOCS_URL}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
class="underline">Learn more</a
|
||||
>
|
||||
</p>
|
||||
{/if}
|
||||
{:else}
|
||||
{@render transformField(spec.key, spec.label, spec.tooltip, spec)}
|
||||
{#if isHistoryKey(spec.key) && !historyInputApplies(spec.key, memoryMode)}
|
||||
<p class="mt-1 text-2xs text-hint">
|
||||
{memoryMode === 'legacy'
|
||||
? legacyMemoryNote
|
||||
: `Ignored while managed memory is ${memoryMode === 'managed' ? 'on' : 'off'}.`}
|
||||
</p>
|
||||
{/if}
|
||||
{#if spec.key === 'enabled_tools' && noToolsEnabled}
|
||||
<div
|
||||
class="mt-1 flex items-center gap-1 text-2xs text-yellow-600 dark:text-yellow-400"
|
||||
>
|
||||
<AlertTriangle size={12} />
|
||||
Nothing selected: the agent runs with no tools.
|
||||
</div>
|
||||
{/if}
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
@@ -51,6 +51,7 @@
|
||||
import ToggleButtonGroup from '$lib/components/common/toggleButton-v2/ToggleButtonGroup.svelte'
|
||||
import ToggleButton from '$lib/components/common/toggleButton-v2/ToggleButton.svelte'
|
||||
import { AI_AGENT_SCHEMA } from '../flowInfers'
|
||||
import { AGENT_HISTORY_KEYS, DEFAULT_AGENT_MEMORY, keepsManagedMemory } from '../agentFormFields'
|
||||
import { nextId } from '../flowModuleNextId'
|
||||
import { fetchAgentWithDraft, normalizeAgentRef } from '../linkedAgentDrafts'
|
||||
import type { AIAgentConfig } from '../agentResourceUtils'
|
||||
@@ -567,7 +568,7 @@
|
||||
return
|
||||
}
|
||||
const missing: string[] = []
|
||||
if (!args.memory || (args.memory as { kind?: string }).kind === 'off') missing.push('memory')
|
||||
if (!keepsManagedMemory(args.memory)) missing.push('memory')
|
||||
if (args.streaming !== true) missing.push('streaming')
|
||||
if (missing.length > 0) {
|
||||
sendUserToast(
|
||||
@@ -604,7 +605,7 @@
|
||||
const aiAgentModules = flowStore.val.value.modules.filter((m) => m.value.type === 'aiagent')
|
||||
|
||||
if (aiAgentModules.length === 0) {
|
||||
// No AI agent exists, create one with context memory set to 10
|
||||
// No AI agent exists, so create one reading the chat's user message
|
||||
const aiAgentId = nextId(flowStateStore.val, flowStore.val)
|
||||
flowStore.val.value.modules = [
|
||||
...flowStore.val.value.modules,
|
||||
@@ -620,10 +621,10 @@
|
||||
} else if (key === 'user_attachments') {
|
||||
accu[key] = { type: 'javascript', expr: `flow_input.${addAttachmentsInput()}` }
|
||||
} else if (key === 'memory') {
|
||||
accu[key] = { type: 'static', value: { kind: 'auto', context_length: 10 } }
|
||||
accu[key] = { type: 'static', value: structuredClone(DEFAULT_AGENT_MEMORY) }
|
||||
} else if (key === 'streaming') {
|
||||
accu[key] = { type: 'static', value: true }
|
||||
} else {
|
||||
} else if (!(AGENT_HISTORY_KEYS as readonly string[]).includes(key)) {
|
||||
accu[key] = {
|
||||
type: 'static',
|
||||
value: undefined
|
||||
@@ -637,7 +638,7 @@
|
||||
}
|
||||
]
|
||||
sendUserToast(
|
||||
'Chat mode enabled. AI agent created with user message and attachments inputs, context memory set to 10 and streaming turned on.',
|
||||
'Chat mode enabled. AI agent created with user message and attachments inputs, managed memory on and streaming turned on.',
|
||||
false
|
||||
)
|
||||
} else if (aiAgentModules.length === 1) {
|
||||
@@ -679,22 +680,29 @@
|
||||
// would be ignored. Those are checked on the agent itself below instead.
|
||||
const linkedAgent = value.agent ? normalizeAgentRef(value.agent) : undefined
|
||||
if (linkedAgent === undefined) {
|
||||
// `off` is the first oneOf variant of the memory field, so a step added by hand
|
||||
// carries it without anyone choosing it — and an agent that forgets every turn
|
||||
// makes the chat a series of unrelated questions. Overwritten rather than left
|
||||
// alone; the toast below says it happened.
|
||||
// `off` is the first oneOf variant, so a step added by hand carries it without anyone
|
||||
// choosing it, and an agent that forgets every turn makes the chat a series of unrelated
|
||||
// questions: overwritten, and the toast says so. A step supplying its own history, as
|
||||
// previous messages or a legacy manual list, has chosen it and is left alone.
|
||||
const memoryIsOff = (transform: InputTransform | undefined) =>
|
||||
transform?.type === 'static' && (transform.value as any)?.kind === 'off'
|
||||
transform?.type === 'static' &&
|
||||
(transform.value as any)?.kind !== 'manual' &&
|
||||
!keepsManagedMemory(transform.value)
|
||||
const messages = value.input_transforms['previous_messages']
|
||||
const suppliesHistory =
|
||||
!isUnconfigured(messages) &&
|
||||
!(messages?.type === 'static' && !(messages.value as unknown[] | undefined)?.length)
|
||||
|
||||
if (
|
||||
isUnconfigured(value.input_transforms['memory']) ||
|
||||
memoryIsOff(value.input_transforms['memory'])
|
||||
!suppliesHistory &&
|
||||
(isUnconfigured(value.input_transforms['memory']) ||
|
||||
memoryIsOff(value.input_transforms['memory']))
|
||||
) {
|
||||
value.input_transforms['memory'] = {
|
||||
type: 'static',
|
||||
value: { kind: 'auto', context_length: 10 }
|
||||
value: structuredClone(DEFAULT_AGENT_MEMORY)
|
||||
}
|
||||
applied.push('context memory set to 10')
|
||||
applied.push('managed memory on')
|
||||
}
|
||||
|
||||
// Without streaming the chat has no SSE to read, so a turn shows nothing —
|
||||
@@ -849,7 +857,7 @@
|
||||
<FlowChat
|
||||
onRunFlow={runFlowWithMessage}
|
||||
path={$pathStore}
|
||||
hideSidebar={true}
|
||||
conversationKind="test"
|
||||
inputSchema={flowStore.val.schema}
|
||||
flowModules={flowStore.val.value?.modules}
|
||||
/>
|
||||
|
||||
@@ -130,6 +130,8 @@
|
||||
* surface without a graph — the agent editor, which addresses one tool at a time — would
|
||||
* offer a row whose click lands nowhere. */
|
||||
noToolNavigation?: boolean
|
||||
/** See `FlowCardHeader`. */
|
||||
agentTrail?: Pick<FlowModule, 'id' | 'summary'>[]
|
||||
toolDescription?: string | undefined
|
||||
siblingToolNames?: string[]
|
||||
}
|
||||
@@ -151,6 +153,7 @@
|
||||
staticOnly = false,
|
||||
flowModuleSchemaMap = undefined,
|
||||
noToolNavigation = false,
|
||||
agentTrail = undefined,
|
||||
toolDescription = $bindable(undefined),
|
||||
siblingToolNames = undefined
|
||||
}: Props = $props()
|
||||
@@ -291,6 +294,8 @@
|
||||
}
|
||||
let inputTransformSchemaForm: { setArgs: (nargs: Record<string, any>) => void } | undefined =
|
||||
$state(undefined)
|
||||
// The linked agent's memory, which decides which history inputs the step offers.
|
||||
let linkedAgentMemory: { memory: unknown } | undefined = $state(undefined)
|
||||
|
||||
let reloadError: string | undefined = $state(undefined)
|
||||
async function reload(flowModule: FlowModule) {
|
||||
@@ -844,6 +849,7 @@
|
||||
on:reload={reloadModule}
|
||||
bind:summary={flowModule.summary}
|
||||
bind:description={toolDescription}
|
||||
{agentTrail}
|
||||
{isAgentTool}
|
||||
{siblingToolNames}
|
||||
>
|
||||
@@ -1154,6 +1160,8 @@
|
||||
opWorkspace={opWs}
|
||||
flowPath={$pathStore}
|
||||
fromAgentEditor={agentEditorHost?.() != undefined}
|
||||
bind:linkedMemory={linkedAgentMemory}
|
||||
chatInputEnabled={flowStore.val.value?.chat_input_enabled ?? false}
|
||||
bind:agent={
|
||||
() =>
|
||||
flowModule.value.type === 'aiagent'
|
||||
@@ -1235,6 +1243,7 @@
|
||||
chatInputEnabled={flowStore.val.value?.chat_input_enabled ?? false}
|
||||
workspace={opWs}
|
||||
visibilityKey={agentFieldsKey}
|
||||
linkedMemory={agentLinked ? linkedAgentMemory : undefined}
|
||||
tools={agentLinked
|
||||
? getLinkedAgentTools(
|
||||
linkedToolsScope(opWs, $pathStore),
|
||||
@@ -1248,6 +1257,10 @@
|
||||
? (detail) =>
|
||||
flowModuleSchemaMap?.addToolToAgent(flowModule.id, detail)
|
||||
: undefined}
|
||||
onDeleteTool={flowModuleSchemaMap && !agentLinked
|
||||
? (toolId) =>
|
||||
flowModuleSchemaMap?.deleteAgentTool(flowModule.id, toolId)
|
||||
: undefined}
|
||||
/>
|
||||
{:else}
|
||||
<InputTransformSchemaForm
|
||||
|
||||
@@ -26,6 +26,7 @@
|
||||
import type { TriggerContext } from '$lib/components/triggers'
|
||||
import { formatCron } from '$lib/utils'
|
||||
import AgentToolWrapper from './AgentToolWrapper.svelte'
|
||||
import { findAgentToolOwner } from '../agentToolTree'
|
||||
const { selectionManager, flowStateStore, opWorkspace } =
|
||||
getContext<FlowEditorContext>('FlowEditorContext')
|
||||
const selectedId = $derived(selectionManager.getSelectedId())
|
||||
@@ -66,6 +67,13 @@
|
||||
flowModuleSchemaMap = undefined
|
||||
}: Props = $props()
|
||||
|
||||
// Searched at any depth: a nested agent's tools have no wrapper of their own to render them.
|
||||
const selectedToolOwner = $derived(
|
||||
flowModule.value.type === 'aiagent' && selectedId
|
||||
? findAgentToolOwner([flowModule], selectedId)
|
||||
: undefined
|
||||
)
|
||||
|
||||
function initializePrimaryScheduleForTriggerScript(module: FlowModule) {
|
||||
const primaryIndex = triggersState.triggers.findIndex((t) => t.isPrimary)
|
||||
if (primaryIndex === -1) {
|
||||
@@ -326,18 +334,19 @@
|
||||
{/if}
|
||||
{/each}
|
||||
{:else if flowModule.value.type === 'aiagent'}
|
||||
{#each flowModule.value.tools ?? [] as tool, toolIndex (toolIndex)}
|
||||
{#if selectedId === tool.id}
|
||||
<AgentToolWrapper
|
||||
{noEditor}
|
||||
bind:tool={flowModule.value.tools![toolIndex]}
|
||||
parentModule={flowModule}
|
||||
{previousModule}
|
||||
{enableAi}
|
||||
{forceTestTab}
|
||||
{highlightArg}
|
||||
siblingToolNames={flowModule.value.tools!.map((t) => t.summary ?? '')}
|
||||
/>
|
||||
{/if}
|
||||
{/each}
|
||||
{#if selectedToolOwner}
|
||||
{@const owner = selectedToolOwner}
|
||||
<AgentToolWrapper
|
||||
{noEditor}
|
||||
bind:tool={() => owner.tools[owner.toolIndex], (v) => (owner.tools[owner.toolIndex] = v)}
|
||||
parentModule={owner.agents[owner.agents.length - 1] as FlowModule}
|
||||
{previousModule}
|
||||
{enableAi}
|
||||
{forceTestTab}
|
||||
{highlightArg}
|
||||
siblingToolNames={owner.tools.map((t) => t.summary ?? '')}
|
||||
agentTrail={owner.agents}
|
||||
{flowModuleSchemaMap}
|
||||
/>
|
||||
{/if}
|
||||
{/if}
|
||||
|
||||
@@ -30,13 +30,16 @@
|
||||
import { getContext, untrack } from 'svelte'
|
||||
import McpConnect from '$lib/components/mcp/McpConnect.svelte'
|
||||
import type { FlowEditorContext } from '../types'
|
||||
import type { FlowModule } from '$lib/gen'
|
||||
|
||||
interface Props {
|
||||
tool: McpTool
|
||||
noEditor?: boolean
|
||||
/** See `FlowCardHeader`. */
|
||||
agentTrail?: Pick<FlowModule, 'id' | 'summary'>[]
|
||||
}
|
||||
|
||||
let { tool = $bindable(), noEditor = false }: Props = $props()
|
||||
let { tool = $bindable(), noEditor = false, agentTrail = undefined }: Props = $props()
|
||||
|
||||
const flowEditorContext = getContext<FlowEditorContext>('FlowEditorContext')
|
||||
let opWs = $derived(flowEditorContext?.opWorkspace?.() ?? $workspaceStore)
|
||||
@@ -91,7 +94,7 @@
|
||||
}
|
||||
</script>
|
||||
|
||||
<FlowCard {noEditor} title="MCP tool">
|
||||
<FlowCard {noEditor} {agentTrail} title="MCP tool">
|
||||
<div class="flex flex-col gap-4 overflow-auto p-4" style="scrollbar-gutter: stable">
|
||||
<div class="w-full">
|
||||
<Label label="MCP resource">
|
||||
|
||||
@@ -1,11 +1,19 @@
|
||||
<script lang="ts">
|
||||
import Alert from '$lib/components/common/alert/Alert.svelte'
|
||||
import type { FlowModule } from '$lib/gen'
|
||||
import FlowCard from '../common/FlowCard.svelte'
|
||||
|
||||
let { noEditor = false }: { noEditor?: boolean } = $props()
|
||||
let {
|
||||
noEditor = false,
|
||||
agentTrail = undefined
|
||||
}: {
|
||||
noEditor?: boolean
|
||||
/** See `FlowCardHeader`. */
|
||||
agentTrail?: Pick<FlowModule, 'id' | 'summary'>[]
|
||||
} = $props()
|
||||
</script>
|
||||
|
||||
<FlowCard {noEditor} title="Web search">
|
||||
<FlowCard {noEditor} {agentTrail} title="Web search">
|
||||
<div class="flex flex-col gap-4 overflow-auto p-4" style="scrollbar-gutter: stable">
|
||||
<Alert title="Web search tool" type="info">
|
||||
Gives the AI Agent the ability to search the web. Only works for openai, anthropic and google
|
||||
|
||||
@@ -28,6 +28,13 @@
|
||||
/** The flow's description, shown under the empty transcript's prompt. */
|
||||
description?: string
|
||||
wideLayout?: boolean
|
||||
/**
|
||||
* What this surface's own runs are: the editor runs previews and lists its test
|
||||
* chats, the flow page runs the deployed flow and lists only its users' chats.
|
||||
* The sidebar offers the kind filter everywhere but on the deployed flow, whose
|
||||
* users have no test chats to look at.
|
||||
*/
|
||||
conversationKind?: 'test' | 'deployed'
|
||||
}
|
||||
|
||||
let {
|
||||
@@ -38,7 +45,8 @@
|
||||
inputSchema = undefined,
|
||||
flowModules = undefined,
|
||||
description = undefined,
|
||||
wideLayout = false
|
||||
wideLayout = false,
|
||||
conversationKind = 'deployed'
|
||||
}: Props = $props()
|
||||
|
||||
const flowEditorContext = getContext<FlowEditorContext>('FlowEditorContext')
|
||||
@@ -97,7 +105,13 @@
|
||||
<div class="flex border border-gray-200 dark:border-gray-700 rounded-lg overflow-hidden flex-1">
|
||||
{#if chat && chatState}
|
||||
{#if !hideSidebar}
|
||||
<FlowConversationsSidebar bind:this={sidebar} {chat} {chatState} />
|
||||
<FlowConversationsSidebar
|
||||
bind:this={sidebar}
|
||||
{chat}
|
||||
{chatState}
|
||||
defaultKind={conversationKind}
|
||||
canFilterKind={conversationKind !== 'deployed'}
|
||||
/>
|
||||
{/if}
|
||||
<!-- The interface's host subscribes to the chat it was given, so a replaced chat
|
||||
(another flow or workspace) mounts a fresh interface rather than a stale host. -->
|
||||
@@ -111,6 +125,7 @@
|
||||
{workspace}
|
||||
{description}
|
||||
{wideLayout}
|
||||
{conversationKind}
|
||||
/>
|
||||
{/key}
|
||||
{/if}
|
||||
|
||||
@@ -32,6 +32,8 @@
|
||||
/** The flow's description, shown under the empty transcript's prompt. */
|
||||
description?: string
|
||||
wideLayout?: boolean
|
||||
/** What this surface's runs create: previews in the editor, deployed runs on the flow page. */
|
||||
conversationKind?: 'test' | 'deployed'
|
||||
}
|
||||
|
||||
let {
|
||||
@@ -42,7 +44,8 @@
|
||||
path,
|
||||
workspace = undefined,
|
||||
description = undefined,
|
||||
wideLayout = false
|
||||
wideLayout = false,
|
||||
conversationKind = 'deployed'
|
||||
}: Props = $props()
|
||||
|
||||
// Derive helperScript for dynamic inputs from schema
|
||||
@@ -150,10 +153,22 @@
|
||||
{
|
||||
additionalInputs: () => (additionalInputsSchema ? { ...runInputs } : undefined),
|
||||
workspace: () => workspace,
|
||||
sendDisabled: () => deploymentInProgress || !!modelGap
|
||||
sendDisabled: () => deploymentInProgress || !!modelGap || !!wrongKindReason
|
||||
}
|
||||
)
|
||||
setChatViewHost(chatHost)
|
||||
|
||||
// A chat of the other kind can be read from here but not added to: the server refuses a
|
||||
// preview run into a deployed conversation and the reverse, so the composer says why first.
|
||||
const wrongKindReason = $derived.by(() => {
|
||||
const { conversationId, conversations } = chatHost.state
|
||||
const open = conversations.find((c) => c.id === conversationId)
|
||||
if (open?.isTest === undefined || open.isTest === (conversationKind === 'test'))
|
||||
return undefined
|
||||
return open.isTest
|
||||
? 'This chat was run from the flow editor. Start a new chat to continue here.'
|
||||
: 'This chat belongs to the deployed flow. Start a new chat to test.'
|
||||
})
|
||||
onDestroy(() => chatHost.dispose())
|
||||
|
||||
// What the Configure-inputs modal asks for: every flow input the composer does not
|
||||
@@ -287,8 +302,10 @@
|
||||
{emptyHint}
|
||||
footerSettings={modalSchema || showModelButton ? footerSettings : undefined}
|
||||
placeholder="Send a message to run the flow"
|
||||
disabled={deploymentInProgress || !!modelGap}
|
||||
disabledMessage={deploymentInProgress ? 'Deployment in progress' : (modelGap ?? '')}
|
||||
disabled={deploymentInProgress || !!modelGap || !!wrongKindReason}
|
||||
disabledMessage={deploymentInProgress
|
||||
? 'Deployment in progress'
|
||||
: (modelGap ?? wrongKindReason ?? '')}
|
||||
loadPastChat={() => {}}
|
||||
deletePastChat={() => {}}
|
||||
saveAndClear={() => {}}
|
||||
|
||||
@@ -1,20 +1,46 @@
|
||||
<script lang="ts">
|
||||
import { Button } from '$lib/components/common'
|
||||
import { MessageCircle, Plus, Trash2, PanelLeftClose, PanelLeftOpen } from 'lucide-svelte'
|
||||
import {
|
||||
MessageCircle,
|
||||
Plus,
|
||||
Trash2,
|
||||
Pen,
|
||||
Filter,
|
||||
PanelLeftClose,
|
||||
PanelLeftOpen
|
||||
} from 'lucide-svelte'
|
||||
import CountBadge from '$lib/components/common/badge/CountBadge.svelte'
|
||||
import InfiniteList from '$lib/components/InfiniteList.svelte'
|
||||
import DropdownV2 from '$lib/components/DropdownV2.svelte'
|
||||
import Popover from '$lib/components/meltComponents/Popover.svelte'
|
||||
import ToggleButtonGroup from '$lib/components/common/toggleButton-v2/ToggleButtonGroup.svelte'
|
||||
import ToggleButton from '$lib/components/common/toggleButton-v2/ToggleButton.svelte'
|
||||
import TextInput from '$lib/components/text_input/TextInput.svelte'
|
||||
import { sendUserToast } from '$lib/toast'
|
||||
import type { Item } from '$lib/utils'
|
||||
import { twMerge } from 'tailwind-merge'
|
||||
import { fade } from 'svelte/transition'
|
||||
import { untrack } from 'svelte'
|
||||
import type { Chat, ChatState, Conversation } from 'windmill-chat'
|
||||
import { tick, untrack } from 'svelte'
|
||||
import type { Chat, ChatState, Conversation, ConversationKind } from 'windmill-chat'
|
||||
|
||||
interface Props {
|
||||
chat: Chat
|
||||
chatState: ChatState
|
||||
/**
|
||||
* Which conversations the list holds at first. The editor shows its own test chats,
|
||||
* since testing is what happens there; a deployed flow shows the chats its users
|
||||
* started, so nobody's trial runs are mixed into them.
|
||||
*/
|
||||
defaultKind?: ConversationKind
|
||||
/**
|
||||
* Whether the filter is offered. Only the editor does: a deployed flow has no test
|
||||
* chats of its own to show, and offering to list someone's trial runs there would
|
||||
* put editor scratch in front of the flow's users.
|
||||
*/
|
||||
canFilterKind?: boolean
|
||||
}
|
||||
|
||||
let { chat, chatState }: Props = $props()
|
||||
let { chat, chatState, defaultKind = 'deployed', canFilterKind = false }: Props = $props()
|
||||
|
||||
let expanded = $state(false)
|
||||
let list = $state<InfiniteList | undefined>(undefined)
|
||||
@@ -23,13 +49,32 @@
|
||||
// A conversation exists on the server only once its first turn ran, so "New chat"
|
||||
// shows a draft row until then.
|
||||
let draft = $state(false)
|
||||
// The prop seeds the filter; the filter is then the user's.
|
||||
let kind = $state<ConversationKind>(untrack(() => defaultKind))
|
||||
|
||||
// The chat being renamed, and the text typed so far. One at a time: the input is the
|
||||
// row's own label, so a second one would have nowhere to go.
|
||||
let renamingId = $state<string | undefined>(undefined)
|
||||
let renameDraft = $state('')
|
||||
let renameInput = $state<TextInput | undefined>(undefined)
|
||||
|
||||
const turnInFlight = $derived(
|
||||
chatState.status === 'submitted' || chatState.status === 'streaming'
|
||||
)
|
||||
|
||||
$effect(() => {
|
||||
const l = list
|
||||
const c = chat
|
||||
if (!l) return
|
||||
untrack(() => {
|
||||
l.setLoader((page, perPage) => c.loadConversations({ page, perPage }))
|
||||
// Every load goes through here, the first one and infinite scroll included. A
|
||||
// response for a kind no longer selected keeps the rows shown: the load for the
|
||||
// selected kind brings its own, whichever of the two lands last.
|
||||
l.setLoader(async (page, perPage) => {
|
||||
const requested = kind
|
||||
const rows = await c.loadConversations({ page, perPage, kind: requested })
|
||||
return requested === kind ? rows : items
|
||||
})
|
||||
l.setDeleteItemFn(async (id: string) => {
|
||||
deletingId = id
|
||||
try {
|
||||
@@ -46,10 +91,15 @@
|
||||
})
|
||||
})
|
||||
|
||||
/** The container reports a started turn: a conversation's first one creates its server entry. */
|
||||
/**
|
||||
* The container reports a started turn: a conversation's first one creates its server
|
||||
* entry. A new conversation is of this surface's own kind, so a filter that would not
|
||||
* list it goes back to that kind rather than hiding the chat that was just started.
|
||||
*/
|
||||
export async function conversationStarted(conversationId: string) {
|
||||
if (items.some((c) => c.id === conversationId)) return
|
||||
draft = false
|
||||
if (kind !== 'all' && kind !== defaultKind) kind = defaultKind
|
||||
await list?.loadData('forceRefresh')
|
||||
}
|
||||
|
||||
@@ -60,6 +110,70 @@
|
||||
draft = true
|
||||
}
|
||||
|
||||
const KIND_LABELS: Record<ConversationKind, string> = {
|
||||
test: 'Test',
|
||||
deployed: 'Deployed',
|
||||
all: 'All'
|
||||
}
|
||||
|
||||
/**
|
||||
* Narrow the list to one kind of chat and reload it. The open conversation goes with it
|
||||
* when it is not of the new kind: the composer sends into whatever is selected, and a
|
||||
* conversation keeps the kind it was created with, so a turn sent into one the list no
|
||||
* longer shows would be stored where nothing here lists it.
|
||||
*/
|
||||
async function setKind(next: ConversationKind) {
|
||||
// A turn writes into the open conversation, which a kind that excludes it would close.
|
||||
if (next === kind || turnInFlight) return
|
||||
kind = next
|
||||
const open = items.find((c) => c.id === chatState.conversationId)
|
||||
const stillListed = open === undefined || next === 'all' || (next === 'test') === open.isTest
|
||||
if (!stillListed) chat.newConversation()
|
||||
await list?.loadData('forceRefresh')
|
||||
}
|
||||
|
||||
async function startRename(conversation: Conversation) {
|
||||
renamingId = conversation.id
|
||||
renameDraft = getConversationTitle(conversation)
|
||||
// The field replaces the row, so it exists only after this render.
|
||||
await tick()
|
||||
renameInput?.focus()
|
||||
renameInput?.select()
|
||||
}
|
||||
|
||||
async function commitRename() {
|
||||
const id = renamingId
|
||||
renamingId = undefined
|
||||
if (!id) return
|
||||
const title = renameDraft.trim()
|
||||
const current = items.find((c) => c.id === id)
|
||||
if (!current || title === '' || title === current.title) return
|
||||
try {
|
||||
await chat.renameConversation(id, title)
|
||||
// The list holds its own rows, loaded through the loader: patched rather than
|
||||
// reloaded, so the row keeps its place without a round trip. The title is read
|
||||
// back from the chat, which holds it as the server stored it (a long one is cut).
|
||||
const stored = chat.getState().conversations.find((c) => c.id === id)?.title ?? title
|
||||
items = items.map((c) => (c.id === id ? { ...c, title: stored } : c))
|
||||
} catch (error) {
|
||||
console.error('Failed to rename conversation:', error)
|
||||
sendUserToast('Failed to rename conversation', true)
|
||||
}
|
||||
}
|
||||
|
||||
function rowActions(conversation: Conversation): Item[] {
|
||||
return [
|
||||
{ displayName: 'Rename', icon: Pen, action: () => startRename(conversation) },
|
||||
{
|
||||
displayName: 'Delete',
|
||||
icon: Trash2,
|
||||
type: 'delete',
|
||||
disabled: deletingId === conversation.id,
|
||||
action: () => list?.deleteItem(conversation.id)
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
function getConversationTitle(conversation: Conversation): string {
|
||||
return conversation.title || `Conversation ${conversation.createdAt.slice(0, 10)}`
|
||||
}
|
||||
@@ -87,17 +201,68 @@
|
||||
>
|
||||
<div transition:fade={{ duration: 100 }}> Conversations </div>
|
||||
</Button>
|
||||
<Button
|
||||
unifiedSize="md"
|
||||
variant="subtle"
|
||||
startIcon={{ icon: Plus, classes: 'ml-[2px]' }}
|
||||
onClick={newChat}
|
||||
title="Start new conversation"
|
||||
iconOnly={!expanded}
|
||||
btnClasses={'justify-start transition-all duration-150 whitespace-nowrap'}
|
||||
>
|
||||
<div transition:fade={{ duration: 100 }}> New chat </div>
|
||||
</Button>
|
||||
<!-- Side by side while there is width for both; stacked once collapsed, where the
|
||||
rail fits one icon across. -->
|
||||
<div class={expanded ? 'flex flex-row gap-1 items-center' : 'flex flex-col gap-2'}>
|
||||
<Button
|
||||
unifiedSize="md"
|
||||
variant="subtle"
|
||||
startIcon={{ icon: Plus, classes: 'ml-[2px]' }}
|
||||
onClick={newChat}
|
||||
title="Start new conversation"
|
||||
iconOnly={!expanded}
|
||||
wrapperClasses={expanded ? 'grow min-w-0' : ''}
|
||||
btnClasses={'w-full justify-start transition-all duration-150 whitespace-nowrap'}
|
||||
>
|
||||
<div transition:fade={{ duration: 100 }}> New chat </div>
|
||||
</Button>
|
||||
{#if canFilterKind}
|
||||
<!-- No focus trap: opening a row's menu does not close this popover, and a
|
||||
trapped popover pulls focus back from the rename field that menu opens. -->
|
||||
<Popover
|
||||
placement="bottom-start"
|
||||
closeButton={false}
|
||||
disableFocusTrap
|
||||
disabled={turnInFlight}
|
||||
>
|
||||
{#snippet trigger()}
|
||||
<!-- Icon-only next to the wider New chat: which kind is listed is named in
|
||||
the title and by the group inside. -->
|
||||
<Button
|
||||
nonCaptureEvent
|
||||
unifiedSize="md"
|
||||
variant="subtle"
|
||||
startIcon={{ icon: Filter }}
|
||||
disabled={turnInFlight}
|
||||
title={turnInFlight
|
||||
? 'Wait for the current answer to change which chats are listed'
|
||||
: `Filter conversations · ${KIND_LABELS[kind]}`}
|
||||
iconOnly
|
||||
/>
|
||||
{/snippet}
|
||||
{#snippet content()}
|
||||
<div class="p-3">
|
||||
<ToggleButtonGroup
|
||||
selected={kind}
|
||||
onSelected={(next) => setKind(next as ConversationKind)}
|
||||
disabled={turnInFlight}
|
||||
noWFull
|
||||
>
|
||||
{#snippet children({ item })}
|
||||
<ToggleButton size="sm" value="test" label={KIND_LABELS.test} {item} />
|
||||
<ToggleButton size="sm" value="deployed" label={KIND_LABELS.deployed} {item} />
|
||||
<ToggleButton size="sm" value="all" label={KIND_LABELS.all} {item} />
|
||||
{/snippet}
|
||||
</ToggleButtonGroup>
|
||||
<p class="text-2xs text-tertiary mt-1.5 max-w-[190px]">
|
||||
Test chats are the ones run from the flow editor's test panel, kept apart from the
|
||||
conversations the deployed flow's users started.
|
||||
</p>
|
||||
</div>
|
||||
{/snippet}
|
||||
</Popover>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -157,38 +322,58 @@
|
||||
{#snippet customRow({ item: conversation })}
|
||||
{#if expanded}
|
||||
<div class={twMerge('w-full pb-1')} transition:fade={{ duration: 100, delay: 30 }}>
|
||||
<Button
|
||||
unifiedSize="md"
|
||||
variant="subtle"
|
||||
onClick={() => {
|
||||
draft = false
|
||||
chat.selectConversation(conversation.id)
|
||||
}}
|
||||
selected={chatState.conversationId === conversation.id}
|
||||
btnClasses="transition-all duration-150 group"
|
||||
>
|
||||
<span class="flex-1 text-left truncate">
|
||||
{getConversationTitle(conversation)}
|
||||
</span>
|
||||
{#if renamingId === conversation.id}
|
||||
<!-- While renaming, the field replaces the row rather than sitting inside its
|
||||
button: a text input nested in a button is a nested interactive control,
|
||||
and every keystroke would have to be kept from reaching the row. -->
|
||||
<div class="flex flex-row items-center h-8 px-2 rounded-md bg-surface-selected">
|
||||
<TextInput
|
||||
bind:this={renameInput}
|
||||
bind:value={renameDraft}
|
||||
class="min-w-0 flex-1"
|
||||
size="sm"
|
||||
inputProps={{
|
||||
'aria-label': 'Chat name',
|
||||
onblur: commitRename,
|
||||
onkeydown: (e: KeyboardEvent) => {
|
||||
if (e.key === 'Enter') {
|
||||
e.preventDefault()
|
||||
commitRename()
|
||||
} else if (e.key === 'Escape') {
|
||||
e.preventDefault()
|
||||
renamingId = undefined
|
||||
}
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
{:else}
|
||||
<Button
|
||||
wrapperClasses={twMerge(
|
||||
'ml-2 transition-all duration-100 opacity-0 group-hover:opacity-100',
|
||||
deletingId === conversation.id ? 'opacity-100' : ' '
|
||||
)}
|
||||
disabled={deletingId === conversation.id}
|
||||
onClick={(e) => {
|
||||
e?.stopPropagation()
|
||||
list?.deleteItem(conversation.id)
|
||||
}}
|
||||
title="Delete conversation"
|
||||
destructive
|
||||
unifiedSize="xs"
|
||||
unifiedSize="md"
|
||||
variant="subtle"
|
||||
loading={deletingId === conversation.id}
|
||||
iconOnly
|
||||
startIcon={{ icon: Trash2 }}
|
||||
/>
|
||||
</Button>
|
||||
onClick={() => {
|
||||
draft = false
|
||||
chat.selectConversation(conversation.id)
|
||||
}}
|
||||
selected={chatState.conversationId === conversation.id}
|
||||
btnClasses="transition-all duration-150 group"
|
||||
>
|
||||
<span class="flex-1 text-left truncate">
|
||||
{getConversationTitle(conversation)}
|
||||
</span>
|
||||
<!-- svelte-ignore a11y_click_events_have_key_events -->
|
||||
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||||
<div
|
||||
class={twMerge(
|
||||
'ml-2 transition-all duration-100 opacity-0 group-hover:opacity-100',
|
||||
deletingId === conversation.id ? 'opacity-100' : ''
|
||||
)}
|
||||
onclick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<DropdownV2 items={() => rowActions(conversation)} size="xs" />
|
||||
</div>
|
||||
</Button>
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
{/snippet}
|
||||
|
||||
@@ -4,6 +4,25 @@ import type { Schema } from '$lib/common'
|
||||
import { emptySchema } from '$lib/utils'
|
||||
import type { FlowModule, InputTransform } from '$lib/gen'
|
||||
import { AGENT_FLOW_LOCAL_KEYS } from './agentResourceUtils'
|
||||
import { AGENT_HISTORY_KEYS } from './agentFormFields'
|
||||
|
||||
/** Display names for the memory field's options, so anything else naming the setting an author
|
||||
* picked cannot drift from the button they see. */
|
||||
export const MEMORY_OPTION_LABELS: Record<string, string> = {
|
||||
off: 'Off',
|
||||
window: 'On',
|
||||
auto: 'On (legacy)',
|
||||
manual: 'Previous messages (legacy)'
|
||||
}
|
||||
|
||||
export function memoryOptionLabel(memory: any): string | undefined {
|
||||
// Managed memory that keeps no messages runs as off, and a note about what that state reads
|
||||
// must say so.
|
||||
if ((memory?.kind === 'window' || memory?.kind === 'auto') && !memory.context_length) {
|
||||
return MEMORY_OPTION_LABELS.off
|
||||
}
|
||||
return memory?.kind ? MEMORY_OPTION_LABELS[memory.kind] : undefined
|
||||
}
|
||||
|
||||
export const AI_AGENT_SCHEMA: Schema = {
|
||||
$schema: 'https://json-schema.org/draft/2020-12/schema',
|
||||
@@ -39,108 +58,86 @@ export const AI_AGENT_SCHEMA: Schema = {
|
||||
},
|
||||
memory: {
|
||||
type: 'object',
|
||||
description:
|
||||
'Windmill stores the conversation and sends its last messages with each request.',
|
||||
enumLabels: MEMORY_OPTION_LABELS,
|
||||
// Chat mode keys memory on the conversation, so a chat whose agent has memory off
|
||||
// forgets every turn. Enabling chat mode sets `auto`; this keeps it there. A step
|
||||
// forgets every turn. Enabling chat mode turns it on; this keeps it there. A step
|
||||
// sitting at `off` stays switchable, or a flow that reached that state before —
|
||||
// an agent added to an already-chat-enabled flow — would have no way out of it.
|
||||
lockOneOfWhenChatEnabled:
|
||||
"Chat mode keys this agent's history on the conversation, so memory stays on while it is enabled.",
|
||||
description: 'History sent between the system message and the user message.',
|
||||
oneOf: [
|
||||
{
|
||||
type: 'object',
|
||||
title: 'off',
|
||||
properties: {
|
||||
kind: {
|
||||
type: 'string',
|
||||
enum: ['off'],
|
||||
description: 'Disable conversation memory'
|
||||
}
|
||||
kind: { type: 'string', enum: ['off'] }
|
||||
}
|
||||
},
|
||||
{
|
||||
type: 'object',
|
||||
title: 'auto',
|
||||
title: 'window',
|
||||
properties: {
|
||||
kind: {
|
||||
type: 'string',
|
||||
enum: ['auto'],
|
||||
default: 'auto',
|
||||
description: 'Automatically manage conversation history'
|
||||
},
|
||||
kind: { type: 'string', enum: ['window'] },
|
||||
context_length: {
|
||||
type: 'number',
|
||||
description:
|
||||
'Number of most recent messages to store and load. Set to 0 to disable memory.',
|
||||
default: 5
|
||||
},
|
||||
memory_id: {
|
||||
type: 'string',
|
||||
format: 'uuid',
|
||||
'x-auto-generate': true,
|
||||
description:
|
||||
'Custom memory identifier. Each unique ID maintains separate conversation history.',
|
||||
hideWhenChatEnabled: true
|
||||
title: 'Messages to keep',
|
||||
description: 'Number of most recent messages to load and store. 0 turns memory off.',
|
||||
default: 10
|
||||
}
|
||||
},
|
||||
required: ['kind'],
|
||||
'x-no-s3-storage-workspace-warning':
|
||||
'When no S3 storage is configured in your workspace settings, memory will be stored in database, which implies a limit of 100KB per memory entry. If you need to store more messages, you should use S3 storage in your workspace settings.'
|
||||
},
|
||||
{
|
||||
type: 'object',
|
||||
title: 'manual',
|
||||
properties: {
|
||||
kind: {
|
||||
type: 'string',
|
||||
enum: ['manual'],
|
||||
description:
|
||||
'Manually provide conversation messages, bypassing automatic memory management'
|
||||
},
|
||||
messages: {
|
||||
type: 'array',
|
||||
description: 'Array of conversation messages to use as history',
|
||||
items: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
role: {
|
||||
type: 'string',
|
||||
enum: ['user', 'assistant', 'system']
|
||||
},
|
||||
content: {
|
||||
type: 'string'
|
||||
},
|
||||
tool_calls: {
|
||||
type: 'array',
|
||||
nullable: true,
|
||||
items: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
id: { type: 'string' },
|
||||
type: { type: 'string' },
|
||||
function: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
name: { type: 'string' },
|
||||
arguments: { type: 'string' }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
tool_call_id: {
|
||||
type: 'string',
|
||||
nullable: true,
|
||||
description: 'The ID of the tool call this message is responding to'
|
||||
required: ['kind', 'context_length']
|
||||
}
|
||||
],
|
||||
showExpr: "fields.output_type !== 'image'"
|
||||
},
|
||||
memory_id: {
|
||||
type: 'string',
|
||||
description:
|
||||
'Names the memory this step reads and writes, overriding the memory id the run was started with. Read only while managed memory is on, and not at all by an older auto or manual memory.',
|
||||
showExpr: "fields.output_type !== 'image'"
|
||||
},
|
||||
previous_messages: {
|
||||
type: 'array',
|
||||
description:
|
||||
'History the flow supplies, sent before the user message. Read only while managed memory is off, and not at all by an older auto or manual memory.',
|
||||
items: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
role: {
|
||||
type: 'string',
|
||||
enum: ['user', 'assistant', 'system']
|
||||
},
|
||||
content: {
|
||||
type: 'string'
|
||||
},
|
||||
tool_calls: {
|
||||
type: 'array',
|
||||
nullable: true,
|
||||
items: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
id: { type: 'string' },
|
||||
type: { type: 'string' },
|
||||
function: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
name: { type: 'string' },
|
||||
arguments: { type: 'string' }
|
||||
}
|
||||
},
|
||||
required: ['role']
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
required: ['kind', 'messages']
|
||||
}
|
||||
],
|
||||
tool_call_id: {
|
||||
type: 'string',
|
||||
nullable: true,
|
||||
description: 'The ID of the tool call this message is responding to'
|
||||
}
|
||||
},
|
||||
required: ['role']
|
||||
},
|
||||
showExpr: "fields.output_type !== 'image'"
|
||||
},
|
||||
output_schema: {
|
||||
@@ -196,6 +193,8 @@ export const AI_AGENT_SCHEMA: Schema = {
|
||||
'system_prompt',
|
||||
'streaming',
|
||||
'memory',
|
||||
'memory_id',
|
||||
'previous_messages',
|
||||
'output_schema',
|
||||
'user_attachments',
|
||||
'enabled_tools',
|
||||
@@ -205,6 +204,48 @@ export const AI_AGENT_SCHEMA: Schema = {
|
||||
]
|
||||
}
|
||||
|
||||
/** Memory shapes older editors wrote. The step form offers one only to a step that still holds it,
|
||||
* since the one-of field rewrites a value that matches none of its options. No field carries a
|
||||
* default: the form writes one into a missing field on open, and a missing count runs as off. */
|
||||
export const LEGACY_MEMORY_VARIANTS: Record<string, any> = {
|
||||
auto: {
|
||||
type: 'object',
|
||||
title: 'auto',
|
||||
properties: {
|
||||
kind: { type: 'string', enum: ['auto'] },
|
||||
context_length: { type: 'number', title: 'Messages to keep' },
|
||||
memory_id: { type: 'string', title: 'Fixed memory id' }
|
||||
},
|
||||
required: ['kind']
|
||||
},
|
||||
manual: {
|
||||
type: 'object',
|
||||
title: 'manual',
|
||||
properties: {
|
||||
kind: { type: 'string', enum: ['manual'] },
|
||||
messages: { type: 'array', items: AI_AGENT_SCHEMA.properties?.previous_messages?.items }
|
||||
},
|
||||
required: ['kind', 'messages']
|
||||
}
|
||||
}
|
||||
|
||||
/** The memory property to render for a value: a legacy kind is added as an option only while the
|
||||
* value holds it. Otherwise the property itself is returned, which callers compare by identity to
|
||||
* avoid rebuilding the step schema. */
|
||||
export function memoryPropertyFor(property: any, value: any, chatInputEnabled = false): any {
|
||||
let legacy = value?.kind ? LEGACY_MEMORY_VARIANTS[value.kind] : undefined
|
||||
if (!legacy || !property?.oneOf) return property
|
||||
// The baked id field is offered only to a value saved with the key (by presence, not content,
|
||||
// or clearing it to retype would remove the field mid-edit), and never in a chat flow, which
|
||||
// runs on the conversation id and drops it on save; there the nested form removes the key on
|
||||
// open, as the hidden field did before.
|
||||
if (value.kind === 'auto' && (chatInputEnabled || !('memory_id' in value))) {
|
||||
const { memory_id: _, ...properties } = legacy.properties
|
||||
legacy = { ...legacy, properties }
|
||||
}
|
||||
return { ...property, oneOf: [...property.oneOf, legacy] }
|
||||
}
|
||||
|
||||
function migrateAiAgentInputTransforms(
|
||||
inputTransforms: Record<string, InputTransform>
|
||||
): Record<string, InputTransform> {
|
||||
@@ -306,10 +347,13 @@ export async function loadSchemaFromModule(
|
||||
: Object.keys(AI_AGENT_SCHEMA.properties ?? {})
|
||||
return {
|
||||
input_transforms: keys.reduce((accu, key) => {
|
||||
accu[key] = input_transforms[key] ?? {
|
||||
type: 'static',
|
||||
value: undefined
|
||||
}
|
||||
const transform =
|
||||
input_transforms[key] ??
|
||||
// A present history input is the step's choice at runtime, so it gets no placeholder.
|
||||
((AGENT_HISTORY_KEYS as readonly string[]).includes(key)
|
||||
? undefined
|
||||
: { type: 'static', value: undefined })
|
||||
if (transform) accu[key] = transform
|
||||
return accu
|
||||
}, {}),
|
||||
// A copy per step, never the shared constant: the form writes back into the property it
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { DEFAULT_AGENT_MEMORY } from './agentFormFields'
|
||||
import type { Schema } from '$lib/common'
|
||||
import {
|
||||
ScriptService,
|
||||
@@ -197,7 +198,8 @@ export async function createBranchAll(id: string): Promise<[FlowModule, FlowModu
|
||||
|
||||
export async function createAiAgent(
|
||||
id: string,
|
||||
agentPath?: string
|
||||
agentPath?: string,
|
||||
chatInputEnabled = false
|
||||
): Promise<[FlowModule, FlowModuleState]> {
|
||||
const storedConfig = loadStoredConfig()
|
||||
const providerValue = storedConfig ?? { kind: 'openai', resource: '', model: '' }
|
||||
@@ -214,7 +216,16 @@ export async function createAiAgent(
|
||||
...(agentPath
|
||||
? {}
|
||||
: {
|
||||
provider: { type: 'static', value: providerValue }
|
||||
provider: { type: 'static', value: providerValue },
|
||||
// A chat agent answers a conversation, so it remembers it from the start.
|
||||
...(chatInputEnabled
|
||||
? {
|
||||
memory: {
|
||||
type: 'static' as const,
|
||||
value: structuredClone(DEFAULT_AGENT_MEMORY)
|
||||
}
|
||||
}
|
||||
: {})
|
||||
}),
|
||||
user_message: { type: 'static', value: undefined }
|
||||
}
|
||||
@@ -491,7 +502,11 @@ export async function createNewModule(
|
||||
} else if (kind == 'branchall') {
|
||||
;[module, state] = await createBranchAll(module.id)
|
||||
} else if (kind == 'aiagent') {
|
||||
;[module, state] = await createAiAgent(module.id, agentPath)
|
||||
;[module, state] = await createAiAgent(
|
||||
module.id,
|
||||
agentPath,
|
||||
flowStore.val.value?.chat_input_enabled ?? false
|
||||
)
|
||||
} else if (inlineScript) {
|
||||
const { language, kind, subkind, summary } = inlineScript
|
||||
;[module, state] = await createInlineScriptModule(language, kind, subkind, module.id, summary)
|
||||
|
||||
@@ -70,6 +70,28 @@ describe('inlineAgentDraft', () => {
|
||||
user_message: { type: 'static', value: 'hi' }
|
||||
})
|
||||
})
|
||||
|
||||
// The worker never reads a history input from the resource, so a preview of the draft must not
|
||||
// either: a draft carrying one would test against a memory the deployed step never sees.
|
||||
it('never takes a history input from the draft', () => {
|
||||
const inlined = inlineAgentDraft(
|
||||
linkedStep({
|
||||
user_message: { type: 'static', value: 'hi' },
|
||||
memory_id: { type: 'static', value: 'cust-1' }
|
||||
}),
|
||||
{
|
||||
memory: { kind: 'window', context_length: 10 },
|
||||
memory_id: 'from-the-draft',
|
||||
previous_messages: [{ role: 'user', content: 'from the draft' }]
|
||||
} as any
|
||||
)
|
||||
|
||||
expect(inlined.input_transforms).toEqual({
|
||||
memory: { type: 'static', value: { kind: 'window', context_length: 10 } },
|
||||
user_message: { type: 'static', value: 'hi' },
|
||||
memory_id: { type: 'static', value: 'cust-1' }
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('inlineAgentDrafts', () => {
|
||||
|
||||
@@ -11,6 +11,7 @@ import { canWrite } from '$lib/utils'
|
||||
import type { UserExt } from '$lib/stores'
|
||||
import { dfs } from './dfs'
|
||||
import { flowLocalInputs, type AIAgentConfig } from './agentResourceUtils'
|
||||
import { AGENT_HISTORY_KEYS } from './agentFormFields'
|
||||
import type { AgentResourceState } from './agentDraft.svelte'
|
||||
import type { AgentTool } from './agentToolUtils'
|
||||
|
||||
@@ -196,17 +197,21 @@ type AiAgentValue = Extract<FlowModule['value'], { type: 'aiagent' }>
|
||||
* the step's own flow-local inputs kept on top.
|
||||
*
|
||||
* The overlay order is the worker's (`ai_executor.rs`): its linked branch interpolates the whole
|
||||
* resource brain and only then writes `user_message`/`user_attachments` back from the step's own
|
||||
* args. `tool_inputs` stays untouched — the worker overlays it onto the tools in both branches, so
|
||||
* an inlined step keeps the host flow's tool bindings.
|
||||
* resource brain and only then writes the flow-local inputs (`user_message`, `user_attachments`,
|
||||
* `enabled_tools`, `memory_id`, `previous_messages`) back from the step's own args. `tool_inputs`
|
||||
* stays untouched — the worker overlays it onto the tools in both branches, so an inlined step
|
||||
* keeps the host flow's tool bindings. The worker never reads a history input from the resource,
|
||||
* so one a draft happens to carry is left out here too.
|
||||
*/
|
||||
export function inlineAgentDraft(value: AiAgentValue, args: AIAgentConfig): AiAgentValue {
|
||||
const { agent: _agent, ...rest } = value
|
||||
const brain = agentArgsToTransforms(args)
|
||||
for (const key of AGENT_HISTORY_KEYS) delete brain[key]
|
||||
return {
|
||||
...rest,
|
||||
tools: (args.tools ?? []) as AgentTool[],
|
||||
input_transforms: {
|
||||
...agentArgsToTransforms(args),
|
||||
...brain,
|
||||
...flowLocalInputs(value.input_transforms as Record<string, InputTransform>)
|
||||
}
|
||||
} as AiAgentValue
|
||||
|
||||
@@ -293,7 +293,7 @@
|
||||
})
|
||||
}
|
||||
|
||||
function requestDelete(ids: string[]) {
|
||||
function requestDelete(ids: string[], selectAfter?: string) {
|
||||
const request = prepareDeleteRequest({
|
||||
ids,
|
||||
flow: flowStore.val,
|
||||
@@ -304,6 +304,9 @@
|
||||
if (!request) {
|
||||
return
|
||||
}
|
||||
if (selectAfter) {
|
||||
request.plan.selection = { kind: 'select', id: selectAfter }
|
||||
}
|
||||
|
||||
const affectedGroups = request.plan.structureDelete?.affectedGroups ?? []
|
||||
|
||||
@@ -325,6 +328,13 @@
|
||||
requestDelete(ids)
|
||||
}
|
||||
|
||||
/** Delete a tool from its agent's Tools section, the only place a nested agent's tools can be
|
||||
* deleted from. The agent stays selected: a plain delete selects whatever precedes the tool,
|
||||
* often a sibling tool, which would take the panel away from the list being edited. */
|
||||
export function deleteAgentTool(agentId: string, toolId: string) {
|
||||
requestDelete([toolId], agentId)
|
||||
}
|
||||
|
||||
// Operates directly on the flat module array (not the structure tree).
|
||||
// Cloned modules are inserted after the originals, intentionally outside any group.
|
||||
export function duplicateMultiple(ids: string[]) {
|
||||
|
||||
@@ -25,6 +25,9 @@
|
||||
kind?: 'script' | 'trigger' | 'preprocessor' | 'failure'
|
||||
allowTrigger?: boolean
|
||||
toolMode?: boolean
|
||||
/** Off for a tool of a nested agent: the worker refuses every call to a nested agent that
|
||||
* carries an agent tool of its own, so offering one would break that nested agent. */
|
||||
allowAiAgentTool?: boolean
|
||||
/** Narrow layout (450px instead of 650px). Defaults on for the preprocessor
|
||||
* and failure pickers; set it when the container cannot fit the wide one. */
|
||||
small?: boolean
|
||||
@@ -37,6 +40,7 @@
|
||||
kind = 'script',
|
||||
allowTrigger = true,
|
||||
toolMode = false,
|
||||
allowAiAgentTool = true,
|
||||
small: smallProp = undefined
|
||||
}: Props = $props()
|
||||
|
||||
@@ -230,13 +234,15 @@
|
||||
dispatch('close')
|
||||
}}
|
||||
/>
|
||||
<TopLevelNode
|
||||
label="AI Agent"
|
||||
onSelect={() => {
|
||||
dispatch('pickAiAgentTool')
|
||||
dispatch('close')
|
||||
}}
|
||||
/>
|
||||
{#if allowAiAgentTool}
|
||||
<TopLevelNode
|
||||
label="AI Agent"
|
||||
onSelect={() => {
|
||||
dispatch('pickAiAgentTool')
|
||||
dispatch('close')
|
||||
}}
|
||||
/>
|
||||
{/if}
|
||||
{:else}
|
||||
{#if customUi?.triggers != false && allowTrigger}
|
||||
<TopLevelNode
|
||||
|
||||
@@ -6,7 +6,6 @@ import {
|
||||
type Job,
|
||||
type RestartedFrom,
|
||||
type OpenFlow,
|
||||
type MemoryConfig,
|
||||
type FlowValue,
|
||||
type Retry
|
||||
} from '$lib/gen'
|
||||
@@ -112,7 +111,6 @@ export function filteredContentForExport(flow: ExtendedOpenFlow) {
|
||||
}
|
||||
|
||||
import { dfs as dfsApply } from './dfs'
|
||||
import { randomUUID } from '$lib/utils/uuid'
|
||||
|
||||
export function cleanFlow(flow: OpenFlow | any): OpenFlow & {
|
||||
tag?: string
|
||||
@@ -141,24 +139,8 @@ export function cleanFlow(flow: OpenFlow | any): OpenFlow & {
|
||||
if (mod.value.type == 'rawscript' && mod.value.assets?.length == 0) {
|
||||
mod.value.assets = undefined
|
||||
}
|
||||
// Generate memory_id for AI agents with auto memory if not already set
|
||||
// Only if chat input is not enabled, as otherwise memory id is based on conversation id
|
||||
if (!newFlow.value.chat_input_enabled && mod.value.type === 'aiagent') {
|
||||
const memoryTransform = mod.value.input_transforms?.memory
|
||||
if (memoryTransform?.type === 'static' && memoryTransform.value) {
|
||||
const memoryValue = memoryTransform.value as MemoryConfig
|
||||
if (
|
||||
memoryValue.kind === 'auto' &&
|
||||
memoryValue.context_length &&
|
||||
memoryValue.context_length > 0 &&
|
||||
!memoryValue.memory_id
|
||||
) {
|
||||
memoryTransform.value = {
|
||||
...memoryValue,
|
||||
memory_id: randomUUID()
|
||||
}
|
||||
}
|
||||
}
|
||||
if (mod.value.type === 'aiagent') {
|
||||
normalizeAgentHistory(mod.value.input_transforms, newFlow.value.chat_input_enabled ?? false)
|
||||
}
|
||||
})
|
||||
if (newFlow.value.concurrency_key == '') {
|
||||
@@ -168,6 +150,43 @@ export function cleanFlow(flow: OpenFlow | any): OpenFlow & {
|
||||
return newFlow
|
||||
}
|
||||
|
||||
/**
|
||||
* A baked legacy id is dropped in a chat flow, which runs on the conversation id; elsewhere it
|
||||
* stays until the author converts it. Blank static history inputs read as unset and managed
|
||||
* memory keeping no messages runs as off, so each is saved as what it runs as.
|
||||
*/
|
||||
export function normalizeAgentHistory(
|
||||
inputTransforms: Record<string, any> | undefined,
|
||||
chatInputEnabled: boolean
|
||||
) {
|
||||
if (!inputTransforms) return
|
||||
const memory = inputTransforms.memory
|
||||
if (
|
||||
memory?.type === 'static' &&
|
||||
memory.value?.kind === 'window' &&
|
||||
!memory.value.context_length
|
||||
) {
|
||||
memory.value = { kind: 'off' }
|
||||
}
|
||||
if (
|
||||
memory?.type === 'static' &&
|
||||
memory.value?.kind === 'auto' &&
|
||||
'memory_id' in memory.value &&
|
||||
(chatInputEnabled || !String(memory.value.memory_id ?? '').trim())
|
||||
) {
|
||||
const { memory_id: _, ...policy } = memory.value
|
||||
memory.value = policy
|
||||
}
|
||||
const memoryId = inputTransforms.memory_id
|
||||
if (memoryId?.type === 'static' && !String(memoryId.value ?? '').trim()) {
|
||||
delete inputTransforms.memory_id
|
||||
}
|
||||
const previousMessages = inputTransforms.previous_messages
|
||||
if (previousMessages?.type === 'static' && !previousMessages.value?.length) {
|
||||
delete inputTransforms.previous_messages
|
||||
}
|
||||
}
|
||||
|
||||
export function getDefaultExpr(
|
||||
key: string = 'myfield',
|
||||
previousModuleId: string | undefined,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import type { FlowValue } from '$lib/gen'
|
||||
import { modulesWithRetryOrSleep } from './utils.svelte'
|
||||
import { modulesWithRetryOrSleep, normalizeAgentHistory } from './utils.svelte'
|
||||
|
||||
const constantRetry = { constant: { attempts: 1, seconds: 5 } }
|
||||
|
||||
@@ -47,3 +47,53 @@ describe('modulesWithRetryOrSleep', () => {
|
||||
expect(modulesWithRetryOrSleep(flow)).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('normalizeAgentHistory', () => {
|
||||
const legacy = () => ({
|
||||
memory: {
|
||||
type: 'static',
|
||||
value: { kind: 'auto', context_length: 10, memory_id: '0f5c3a8e-1d2b-4c6a-9e7f-3b8d2a1c4e6f' }
|
||||
}
|
||||
})
|
||||
|
||||
// Outside chat the baked id is still read for runs that pass none, and an older worker must keep
|
||||
// accepting the step, so a save leaves it exactly as it was.
|
||||
it('keeps a legacy baked memory id outside chat mode', () => {
|
||||
const transforms = legacy()
|
||||
normalizeAgentHistory(transforms, false)
|
||||
expect(transforms).toEqual(legacy())
|
||||
})
|
||||
|
||||
it('drops a legacy baked memory id in chat mode, where it was never read', () => {
|
||||
const transforms = legacy()
|
||||
normalizeAgentHistory(transforms, true)
|
||||
expect(transforms.memory.value).toEqual({ kind: 'auto', context_length: 10 })
|
||||
})
|
||||
|
||||
it('drops an empty baked memory id, which names no memory', () => {
|
||||
const transforms = {
|
||||
memory: { type: 'static', value: { kind: 'auto', context_length: 10, memory_id: '' } }
|
||||
}
|
||||
normalizeAgentHistory(transforms, false)
|
||||
expect(transforms.memory.value).toEqual({ kind: 'auto', context_length: 10 })
|
||||
})
|
||||
|
||||
it('saves managed memory that keeps no messages as off, which is how it runs', () => {
|
||||
for (const context_length of [0, null, undefined]) {
|
||||
const transforms: Record<string, any> = {
|
||||
memory: { type: 'static', value: { kind: 'window', context_length } }
|
||||
}
|
||||
normalizeAgentHistory(transforms, false)
|
||||
expect(transforms.memory.value).toEqual({ kind: 'off' })
|
||||
}
|
||||
})
|
||||
|
||||
it('does not persist an empty static memory id or message list', () => {
|
||||
const transforms: Record<string, any> = {
|
||||
memory_id: { type: 'static', value: ' ' },
|
||||
previous_messages: { type: 'static', value: [] }
|
||||
}
|
||||
normalizeAgentHistory(transforms, false)
|
||||
expect(transforms).toEqual({})
|
||||
})
|
||||
})
|
||||
|
||||
+52
-8
@@ -533,9 +533,30 @@ components:
|
||||
required:
|
||||
- kind
|
||||
|
||||
MemoryWindow:
|
||||
type: object
|
||||
description: |
|
||||
Keeps the most recent messages of the memory named by the run's memory id (or the step's
|
||||
`memory_id`). Without a memory id the agent runs without memory.
|
||||
properties:
|
||||
kind:
|
||||
type: string
|
||||
enum:
|
||||
- window
|
||||
context_length:
|
||||
type: integer
|
||||
description: Number of most recent messages to load and store. 0 turns memory off.
|
||||
required:
|
||||
- kind
|
||||
- context_length
|
||||
|
||||
MemoryAuto:
|
||||
type: object
|
||||
description: Automatic context management
|
||||
deprecated: true
|
||||
description: |
|
||||
Deprecated, still read as it was written: the run's memory id, else the `memory_id` here.
|
||||
The step's own `memory_id` is not read while this kind is set; switch the kind to `window`
|
||||
to use it. Without a `context_length`, or with 0, it is `off` and reads `previous_messages`.
|
||||
properties:
|
||||
kind:
|
||||
type: string
|
||||
@@ -568,7 +589,8 @@ components:
|
||||
|
||||
MemoryManual:
|
||||
type: object
|
||||
description: Explicit message history
|
||||
deprecated: true
|
||||
description: Deprecated, still read as it was written. Move the step to `off` with `previous_messages` instead.
|
||||
properties:
|
||||
kind:
|
||||
type: string
|
||||
@@ -583,15 +605,17 @@ components:
|
||||
- messages
|
||||
|
||||
MemoryConfig:
|
||||
description: Conversation memory configuration
|
||||
description: Managed memory, stored by Windmill and replayed with each request. The memory is named by a memory id, see `memory_id`. While it is off, a step can supply its history in `previous_messages`.
|
||||
oneOf:
|
||||
- $ref: '#/components/schemas/MemoryOff'
|
||||
- $ref: '#/components/schemas/MemoryWindow'
|
||||
- $ref: '#/components/schemas/MemoryAuto'
|
||||
- $ref: '#/components/schemas/MemoryManual'
|
||||
discriminator:
|
||||
propertyName: kind
|
||||
mapping:
|
||||
'off': '#/components/schemas/MemoryOff'
|
||||
window: '#/components/schemas/MemoryWindow'
|
||||
auto: '#/components/schemas/MemoryAuto'
|
||||
manual: '#/components/schemas/MemoryManual'
|
||||
|
||||
@@ -1041,7 +1065,10 @@ components:
|
||||
user_message:
|
||||
allOf:
|
||||
- $ref: '#/components/schemas/InputTransform'
|
||||
description: The user's prompt/message to the AI agent. Supports variable interpolation with flow.input syntax.
|
||||
description: |
|
||||
The user's prompt/message to the AI agent. Supports variable interpolation with
|
||||
flow.input syntax. Required unless memory is off and `previous_messages` supplies
|
||||
the prompt; image output always needs it.
|
||||
system_prompt:
|
||||
allOf:
|
||||
- $ref: '#/components/schemas/InputTransform'
|
||||
@@ -1054,6 +1081,24 @@ components:
|
||||
Streaming events include: token_delta, reasoning_token_delta, tool_call, tool_call_arguments, tool_execution, tool_result
|
||||
memory:
|
||||
$ref: '#/components/schemas/MemoryTransform'
|
||||
memory_id:
|
||||
allOf:
|
||||
- $ref: '#/components/schemas/InputTransform'
|
||||
description: |
|
||||
String. Names the memory this step reads and writes, overriding the memory id the run
|
||||
was started with (the chat conversation, an app chat session or the `memory_id` run
|
||||
parameter). Leave unset to use the run's memory id. A fixed value shares one memory
|
||||
across every run; an expression such as `flow_input.customer_id` keeps one memory per
|
||||
key. When it evaluates to an empty value the agent runs without memory. Read only
|
||||
while `memory` is `window`: it is ignored when memory is off, and an older `auto` or
|
||||
`manual` memory reads neither history input.
|
||||
previous_messages:
|
||||
allOf:
|
||||
- $ref: '#/components/schemas/InputTransform'
|
||||
description: |
|
||||
Array of MemoryMessage. History supplied by the flow, sent between the system prompt
|
||||
and the user message. Read only while `memory` is off or absent: managed memory
|
||||
ignores it, and an older `auto` or `manual` memory reads neither history input.
|
||||
output_schema:
|
||||
allOf:
|
||||
- $ref: '#/components/schemas/InputTransform'
|
||||
@@ -1102,9 +1147,8 @@ components:
|
||||
Number. Limits how many times the agent can loop through reasoning and tool use.
|
||||
Range: 1-1000.
|
||||
# Only the flow-local inputs are always present: a step linked to an `ai_agent` resource
|
||||
# (see `agent`) keeps just those and takes provider/output_type from the resource.
|
||||
required:
|
||||
- user_message
|
||||
# (see `agent`) keeps just those and takes provider/output_type from the resource. Even
|
||||
# `user_message` may be absent, when memory is off and `previous_messages` is the prompt.
|
||||
tools:
|
||||
type: array
|
||||
description: Array of tools the agent can use. The agent decides which tools to call based on the task
|
||||
@@ -1127,7 +1171,7 @@ components:
|
||||
Path of a reusable `ai_agent` resource (hybrid linking). When set, the agent brain
|
||||
config (provider/model/system prompt/etc.) and tool set are resolved at runtime from
|
||||
that resource; the module's input_transforms then only carry the flow-local inputs
|
||||
(user_message/user_attachments/enabled_tools).
|
||||
(user_message, user_attachments, enabled_tools and the history inputs memory_id and previous_messages).
|
||||
tool_inputs:
|
||||
type: object
|
||||
description: |
|
||||
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -135,7 +135,7 @@ needs becomes unreachable.
|
||||
},
|
||||
"user_message": { "type": "javascript", "expr": "flow_input.user_message" },
|
||||
"user_attachments": { "type": "javascript", "expr": "flow_input.files" },
|
||||
"memory": { "type": "static", "value": { "kind": "auto", "context_length": 10 } },
|
||||
"memory": { "type": "static", "value": { "kind": "window", "context_length": 10 } },
|
||||
"streaming": { "type": "static", "value": true },
|
||||
"output_type": { "type": "static", "value": "text" }
|
||||
},
|
||||
|
||||
Reference in New Issue
Block a user