π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
π fix(lobe-agent): infer omitted todo operation type and fail loudly on invalid updateTodos ops (#18967)
Arvin Xu7716f4009823
diff --git a/packages/builtin-tool-lobe-agent/package.json b/packages/builtin-tool-lobe-agent/package.jsonindex 4e072fd4e0d..184a6417bdc 100644--- a/packages/builtin-tool-lobe-agent/package.json+++ b/packages/builtin-tool-lobe-agent/package.json@@ -6,7 +6,7 @@".": "./src/index.ts","./client": "./src/client/index.ts","./client/executor": "./src/client/executor/index.ts",- "./planRuntime": "./src/client/executor/PlanRuntime/index.ts"+ "./planRuntime": "./src/PlanRuntime/index.ts"},"main": "./src/index.ts","scripts": {diff --git a/packages/builtin-tool-lobe-agent/src/client/executor/PlanRuntime/index.ts b/packages/builtin-tool-lobe-agent/src/PlanRuntime/index.tssimilarity index 71%rename from packages/builtin-tool-lobe-agent/src/client/executor/PlanRuntime/index.tsrename to packages/builtin-tool-lobe-agent/src/PlanRuntime/index.tsindex e6c3a42b5aa..c0e9671af10 100644--- a/packages/builtin-tool-lobe-agent/src/client/executor/PlanRuntime/index.ts+++ b/packages/builtin-tool-lobe-agent/src/PlanRuntime/index.ts@@ -8,9 +8,10 @@ import type {Plan,TodoItem,TodoState,+ TodoUpdateOperation,UpdatePlanParams,UpdateTodosParams,-} from '../../../types';+} from '../types';export interface PlanDocument {content: string | null;@@ -71,6 +72,22 @@ const toPlan = (doc: PlanDocument, completed = false): Plan => ({updatedAt: doc.updatedAt.toISOString(),});+/**+ * Weak instruction-following models drop the required `type` discriminator+ * while still sending an unambiguous payload (production example from+ * glm-5.3-flash: `{"index": 0, "status": "processing"}`). Infer the operation+ * type where the intent is unambiguous; index-only payloads stay undefined β+ * they could equally mean `remove` or `complete`, and guessing a destructive+ * operation is worse than asking the model to retry.+ */+const inferOperationType = (op: TodoUpdateOperation): TodoUpdateOperation['type'] | undefined => {+ if (op.type) return op.type;+ if (op.index !== undefined && (op.status !== undefined || op.newText !== undefined))+ return 'update';+ if (op.index === undefined && op.text !== undefined) return 'add';+ return undefined;+};+const readTodosFromPlan = (doc: PlanDocument | null): TodoItem[] => {const todos = doc?.metadata?.todos;if (!todos) return [];@@ -160,62 +177,114 @@ export class PlanExecutionRuntime {const existingTodos = await this.resolveExistingTodos(context);const updatedTodos = [...existingTodos];const results: string[] = [];+ const skipped: string[] = [];++ operations.forEach((op, position) => {+ const label = `Operation ${position + 1}`;+ const type = inferOperationType(op);++ const resolveIndex = (): number | undefined => {+ if (op.index !== undefined && op.index >= 0 && op.index < updatedTodos.length)+ return op.index;+ skipped.push(+ `${label} ("${type}"): "index" must be 0-${updatedTodos.length - 1}, got ${op.index ?? 'nothing'}`,+ );+ return undefined;+ };- for (const op of operations) {- switch (op.type) {+ switch (type) {case 'add': {if (op.text) {updatedTodos.push({ status: 'todo', text: op.text });results.push(`Added: "${op.text}"`);+ } else {+ skipped.push(`${label} ("add"): missing "text"`);}break;}case 'update': {- if (op.index !== undefined && op.index >= 0 && op.index < updatedTodos.length) {- const updatedItem = { ...updatedTodos[op.index] };+ // An update that carries neither field would "apply" without changing+ // anything β the same silent success this whole branch exists to kill.+ if (op.newText === undefined && op.status === undefined) {+ skipped.push(+ `${label} ("update"): provide "newText" and/or "status" (use "remove"/"complete" to drop or finish an item)`,+ );+ break;+ }+ const index = resolveIndex();+ if (index !== undefined) {+ const updatedItem = { ...updatedTodos[index] };if (op.newText !== undefined) updatedItem.text = op.newText;if (op.status !== undefined) updatedItem.status = op.status;- updatedTodos[op.index] = updatedItem;- results.push(`Updated item ${op.index + 1}`);+ updatedTodos[index] = updatedItem;+ results.push(`Updated item ${index + 1}`);}break;}case 'remove': {- if (op.index !== undefined && op.index >= 0 && op.index < updatedTodos.length) {- const removed = updatedTodos.splice(op.index, 1)[0];+ const index = resolveIndex();+ if (index !== undefined) {+ const removed = updatedTodos.splice(index, 1)[0];results.push(`Removed: "${removed.text}"`);}break;}case 'complete': {- if (op.index !== undefined && op.index >= 0 && op.index < updatedTodos.length) {- updatedTodos[op.index] = { ...updatedTodos[op.index], status: 'completed' };- results.push(`Completed: "${updatedTodos[op.index].text}"`);+ const index = resolveIndex();+ if (index !== undefined) {+ updatedTodos[index] = { ...updatedTodos[index], status: 'completed' };+ results.push(`Completed: "${updatedTodos[index].text}"`);}break;}case 'processing': {- if (op.index !== undefined && op.index >= 0 && op.index < updatedTodos.length) {- updatedTodos[op.index] = { ...updatedTodos[op.index], status: 'processing' };- results.push(`In progress: "${updatedTodos[op.index].text}"`);+ const index = resolveIndex();+ if (index !== undefined) {+ updatedTodos[index] = { ...updatedTodos[index], status: 'processing' };+ results.push(`In progress: "${updatedTodos[index].text}"`);}break;}+ default: {+ skipped.push(+ `${label}: "type" is required and must be one of add / update / remove / complete / processing, e.g. {"type": "update", "index": 0, "status": "processing"}`,+ );+ }}- }+ });const now = new Date().toISOString();- const actionSummary =- results.length > 0- ? `π Applied ${results.length} operation${results.length > 1 ? 's' : ''}:\n${results.map((r) => `- ${r}`).join('\n')}`- : 'No operations applied.';+ const skippedSummary =+ skipped.length > 0+ ? `β οΈ Skipped ${skipped.length} invalid operation${skipped.length > 1 ? 's' : ''}:\n${skipped.map((r) => `- ${r}`).join('\n')}`+ : '';++ // Every operation was invalid: fail loudly so the model can fix its+ // arguments and retry, instead of reading a "success" that changed nothing+ // (observed in production: 5 identical retries against a silent no-op).+ if (results.length === 0) {+ return {+ content: [+ 'No operations applied.',+ skippedSummary,+ formatTodoStateSummary(existingTodos, now),+ ]+ .filter(Boolean)+ .join('\n\n'),+ success: false,+ };+ }++ const actionSummary = `π Applied ${results.length} operation${results.length > 1 ? 's' : ''}:\n${results.map((r) => `- ${r}`).join('\n')}`;const todoState: TodoState = { items: updatedTodos, updatedAt: now };if (context.topicId) await this.syncTodosToPlan(context.topicId, todoState);return {- content: actionSummary + '\n\n' + formatTodoStateSummary(updatedTodos, now),+ content: [actionSummary, skippedSummary, formatTodoStateSummary(updatedTodos, now)]+ .filter(Boolean)+ .join('\n\n'),state: { todos: todoState },success: true,};diff --git a/packages/builtin-tool-lobe-agent/src/client/executor/PlanRuntime/serverTodoPersistence.test.ts b/packages/builtin-tool-lobe-agent/src/PlanRuntime/serverTodoPersistence.test.tssimilarity index 100%rename from packages/builtin-tool-lobe-agent/src/client/executor/PlanRuntime/serverTodoPersistence.test.tsrename to packages/builtin-tool-lobe-agent/src/PlanRuntime/serverTodoPersistence.test.tsdiff --git a/packages/builtin-tool-lobe-agent/src/PlanRuntime/updateTodos.test.ts b/packages/builtin-tool-lobe-agent/src/PlanRuntime/updateTodos.test.tsnew file mode 100644index 00000000000..3ee9f9cb28b--- /dev/null+++ b/packages/builtin-tool-lobe-agent/src/PlanRuntime/updateTodos.test.ts@@ -0,0 +1,115 @@+import { describe, expect, it, vi } from 'vitest';++import type { TodoItem } from '../types';+import type { PlanRuntimeService } from './index';+import { PlanExecutionRuntime } from './index';++/**+ * `updateTodos` used to `switch (op.type)` and silently skip any operation the+ * switch didn't match, then answer `success: true` + "No operations applied.".+ * In production glm-5.3-flash dropped the required `type` discriminator+ * (`{"index": 0, "status": "processing"}`), got a "success" that changed+ * nothing, and retried the identical call five times before giving up on the+ * tool entirely. The runtime now infers an unambiguous type, reports every+ * skipped operation with the reason, and fails loudly when nothing applied.+ */+const createRuntime = () =>+ new PlanExecutionRuntime({+ createPlan: vi.fn(),+ findPlanById: vi.fn(),+ findPlanByTopic: vi.fn().mockResolvedValue(null),+ updatePlan: vi.fn(),+ updatePlanMetadata: vi.fn(),+ } as unknown as PlanRuntimeService);++const currentTodos: TodoItem[] = [+ { status: 'todo', text: 'create linear issues' },+ { status: 'todo', text: 'cut worktree' },+];++const context = { currentTodos, messageId: 'msg_1', topicId: 'tpc_1' };++describe('updateTodos type inference', () => {+ it('applies an index+status operation that omits "type" as an update', async () => {+ const runtime = createRuntime();++ const result = await runtime.updateTodos(+ { operations: [{ index: 0, status: 'processing' }] },+ context,+ );++ expect(result.success).toBe(true);+ expect(result.content).not.toContain('No operations applied.');+ expect((result.state as any).todos.items[0].status).toBe('processing');+ });++ it('applies a text-only operation that omits "type" as an add', async () => {+ const runtime = createRuntime();++ const result = await runtime.updateTodos({ operations: [{ text: 'open the PR' }] }, context);++ expect(result.success).toBe(true);+ expect((result.state as any).todos.items).toHaveLength(3);+ expect((result.state as any).todos.items[2]).toEqual({ status: 'todo', text: 'open the PR' });+ });++ it('does not guess between remove/complete for an index-only operation', async () => {+ const runtime = createRuntime();++ const result = await runtime.updateTodos({ operations: [{ index: 0 }] }, context);++ expect(result.success).toBe(false);+ expect(result.content).toContain('"type" is required');+ // Nothing changed, so no state is written β the previous pluginState.todos+ // stays the newest copy in message history.+ expect(result.state).toBeUndefined();+ });+});++describe('updateTodos invalid-operation reporting', () => {+ it('rejects an update that carries neither newText nor status', async () => {+ const runtime = createRuntime();++ const result = await runtime.updateTodos(+ { operations: [{ index: 0, type: 'update' }] },+ context,+ );++ expect(result.success).toBe(false);+ expect(result.content).toContain('No operations applied.');+ expect(result.content).toContain('provide "newText" and/or "status"');+ expect(result.state).toBeUndefined();+ });++ it('fails with the reason when every operation is invalid', async () => {+ const runtime = createRuntime();++ const result = await runtime.updateTodos(+ { operations: [{ index: 5, type: 'complete' }] },+ context,+ );++ expect(result.success).toBe(false);+ expect(result.content).toContain('No operations applied.');+ expect(result.content).toContain('"index" must be 0-1, got 5');+ });++ it('reports skipped operations alongside applied ones', async () => {+ const runtime = createRuntime();++ const result = await runtime.updateTodos(+ {+ operations: [+ { index: 0, type: 'complete' },+ { index: 9, type: 'remove' },+ ],+ },+ context,+ );++ expect(result.success).toBe(true);+ expect(result.content).toContain('Applied 1 operation');+ expect(result.content).toContain('Skipped 1 invalid operation');+ expect((result.state as any).todos.items[0].status).toBe('completed');+ });+});diff --git a/packages/builtin-tool-lobe-agent/src/client/executor/index.ts b/packages/builtin-tool-lobe-agent/src/client/executor/index.tsindex 614c0aca898..98d1b50652c 100644--- a/packages/builtin-tool-lobe-agent/src/client/executor/index.ts+++ b/packages/builtin-tool-lobe-agent/src/client/executor/index.ts@@ -35,7 +35,7 @@ import {PlanExecutionRuntime,type PlanRuntimeContext,type PlanRuntimeService,-} from './PlanRuntime';+} from '../../PlanRuntime';import { getTodosFromContext } from './planTodoHelper';import { resolveClientMediaPayloadItems } from './resolveMediaUris';diff --git a/packages/builtin-tool-lobe-agent/src/index.ts b/packages/builtin-tool-lobe-agent/src/index.tsindex 9a8d543242c..589afeb5fc8 100644--- a/packages/builtin-tool-lobe-agent/src/index.ts+++ b/packages/builtin-tool-lobe-agent/src/index.ts@@ -3,7 +3,7 @@ export {type PlanDocument,type PlanRuntimeContext,type PlanRuntimeService,-} from './client/executor/PlanRuntime';+} from './PlanRuntime';export * from './manifest';export * from './media';export * from './resolveManifest';diff --git a/packages/builtin-tool-lobe-agent/src/types.ts b/packages/builtin-tool-lobe-agent/src/types.tsindex b062a58e0c7..c590303927e 100644--- a/packages/builtin-tool-lobe-agent/src/types.ts+++ b/packages/builtin-tool-lobe-agent/src/types.ts@@ -158,8 +158,12 @@ export interface TodoUpdateOperation {status?: TodoStatus;/** For 'add': the text to add */text?: string;- /** Operation type */- type: TodoUpdateOperationType;+ /**+ * Operation type. Required by the manifest schema, but weak+ * instruction-following models omit it in practice, so the runtime infers it+ * from the other fields when the intent is unambiguous.+ */+ type?: TodoUpdateOperationType;}/**