diff --git a/docs/api/routines.md b/docs/api/routines.md index 61b838cc133..8e2815bfdfb 100644 --- a/docs/api/routines.md +++ b/docs/api/routines.md @@ -187,6 +187,8 @@ POST /api/routines/{routineId}/run Fires a run immediately, bypassing the schedule. Concurrency policy still applies. +A run an agent starts through this endpoint is always recorded with source `manual`; the server ignores a `source` value an agent sends. Board callers may send `manual` or `api`. + `triggerId` is optional. When supplied, the server validates the trigger belongs to this routine (`403`) and is enabled (`409`), then records the run against that trigger and updates its `lastFiredAt`. Omit it for a generic manual run with no trigger attribution. ## Fire Public Trigger diff --git a/server/src/__tests__/agent-conversations.test.ts b/server/src/__tests__/agent-conversations.test.ts index 2472fa89b1c..40ec0af690a 100644 --- a/server/src/__tests__/agent-conversations.test.ts +++ b/server/src/__tests__/agent-conversations.test.ts @@ -995,6 +995,11 @@ describe("chat prompt policy", () => { const prompt = buildPaperclipTaskMarkdown({ issue: { id: "chat", identifier: null, title: "Chat", workMode: "ask", conversationAgentId: "agent" } }); expect(prompt).toContain("Write replies for the person, not for the API."); }); + it("tells chat to name a document revision by its number and to link a run it discusses, while keeping raw IDs out of prose", () => { + expect(AGENT_CHAT_DIRECTIVE).toContain("Name a document revision by its number as Paperclip shows it, such as revision 4, including the revision a restore or edit created."); + expect(AGENT_CHAT_DIRECTIVE).toContain("When you discuss a run, such as a failed or retried run, link it, such as [the failed run](//agents//runs/), instead of describing it without a link."); + expect(AGENT_CHAT_DIRECTIVE).toContain("Do not write raw IDs (UUIDs or their short forms for runs, revisions,"); + }); it("tells chat to record a person's decline with resolve-from-comment whoever created the card, and keeps withdraw for its own obsolete card", () => { expect(AGENT_CHAT_DIRECTIVE).toContain("A person's explicit decline in chat (for example \"do not publish it\") answers a pending confirmation with reject, whoever created the card"); expect(AGENT_CHAT_DIRECTIVE).toContain("Withdraw is only for your own card that later evidence made obsolete; it never records the person's decision"); diff --git a/server/src/__tests__/routines-routes.test.ts b/server/src/__tests__/routines-routes.test.ts index bef72fb8046..831e13872ba 100644 --- a/server/src/__tests__/routines-routes.test.ts +++ b/server/src/__tests__/routines-routes.test.ts @@ -702,6 +702,17 @@ describe("routine routes", () => { }); }); + it("records an agent-started run as manual whatever source the agent sends, and keeps a board caller's source", async () => { + const agentApp = await createApp({ type: "agent", agentId, companyId }); + const res = await request(agentApp).post(`/api/routines/${routineId}/run`).send({ source: "api" }); + expect(res.status, JSON.stringify(res.body)).toBe(202); + expect(mockRoutineService.runRoutine).toHaveBeenLastCalledWith(routineId, expect.objectContaining({ source: "manual" }), expect.objectContaining({ agentId })); + mockAccessService.canUser.mockResolvedValue(true); + const boardApp = await createApp({ type: "board", userId: "board-user", source: "session", isInstanceAdmin: false, companyIds: [companyId] }); + expect((await request(boardApp).post(`/api/routines/${routineId}/run`).send({ source: "api" })).status).toBe(202); + expect(mockRoutineService.runRoutine).toHaveBeenLastCalledWith(routineId, expect.objectContaining({ source: "api" }), expect.objectContaining({ userId: "board-user" })); + }); + it("allows routine creation when the board user has tasks:assign", async () => { mockAccessService.canUser.mockResolvedValue(true); const app = await createApp({ diff --git a/server/src/__tests__/routines-service.test.ts b/server/src/__tests__/routines-service.test.ts index a8f50daa868..5ac0a62f0ae 100644 --- a/server/src/__tests__/routines-service.test.ts +++ b/server/src/__tests__/routines-service.test.ts @@ -1198,6 +1198,23 @@ describeEmbeddedPostgres("routine service live-execution coalescing", () => { expect(serialized).not.toContain("runtimeConfig"); }); + it("returns only the same agent's earlier api receipt when it retries its key as a manual run", async () => { + const { companyId, routine, svc, agentId } = await seedFixture(); + await db.update(routines).set({ concurrencyPolicy: "always_enqueue" }).where(eq(routines.id, routine.id)); + const boardApi = await svc.runRoutine(routine.id, { source: "api", idempotencyKey: "shared-key" }, { userId: "operator" }); + await db.insert(activityLog).values({ companyId, actorType: "user", actorId: "operator", action: "routine.run_triggered", entityType: "routine_run", entityId: boardApi.id }); + await db.update(issues).set({ status: "done" }).where(eq(issues.id, boardApi.linkedIssueId!)); + const agentRun = await svc.runRoutine(routine.id, { source: "manual", idempotencyKey: "shared-key" }, { agentId }); + expect(agentRun.id).not.toBe(boardApi.id); + const earlier = await svc.runRoutine(routine.id, { source: "api", idempotencyKey: "agent-retry" }, { agentId }); + await db.insert(activityLog).values({ companyId, actorType: "agent", actorId: agentId, agentId, action: "routine.run_triggered", entityType: "routine_run", entityId: earlier.id }); + await db.update(issues).set({ status: "done" }).where(eq(issues.id, earlier.linkedIssueId!)); + const retry = await svc.runRoutine(routine.id, { source: "manual", idempotencyKey: "agent-retry" }, { agentId }); + expect(retry.id).toBe(earlier.id); + const board = await svc.runRoutine(routine.id, { source: "manual", idempotencyKey: "agent-retry" }, { userId: "operator" }); + expect(board.id).not.toBe(earlier.id); + }); + it("versions responsibility transfers and uses the new person only for future automatic tasks", async () => { const { companyId, routine, svc } = await seedFixture(); const userId = "new-responsible-person"; diff --git a/server/src/routes/routines.ts b/server/src/routes/routines.ts index c798c2f4ed4..07b14ee585b 100644 --- a/server/src/routes/routines.ts +++ b/server/src/routes/routines.ts @@ -662,7 +662,8 @@ export function routineRoutes( return; } await assertBoardCanAssignTasks(req, routine.companyId); - const run = await svc.runRoutine(routine.id, req.body, { + const input = req.actor.type === "agent" ? { ...req.body, source: "manual" as const } : req.body; + const run = await svc.runRoutine(routine.id, input, { agentId: req.actor.type === "agent" ? req.actor.agentId : null, userId: req.actor.type === "board" ? req.actor.userId ?? null : null, runId: req.actor.runId ?? null, diff --git a/server/src/services/agent-conversations.ts b/server/src/services/agent-conversations.ts index c9330363d32..60b4d9a3f50 100644 --- a/server/src/services/agent-conversations.ts +++ b/server/src/services/agent-conversations.ts @@ -128,7 +128,7 @@ When a reply concerns a specific agent, such as one you paused, resumed, configu When a reply lists many tasks, write each task identifier in full, such as RUN-12, RUN-13, RUN-14. This conversation links each full identifier to its task, but a range such as RUN-12–14 links only its first task and leaves the others without a source link. When a complete list is too long to read in the reply, save it as a document on this conversation's task and link it, such as [Open work by owner](//issues/#document-), keeping a short summary with the counts in the reply. -Write replies for the person, not for the API. Name each record by what the person sees in Paperclip: a task, case or approval by its identifier (such as RUN-12) or title, a person or agent by name, and link it. Do not write raw IDs (UUIDs or their short forms for runs, revisions, handoffs, interactions, routines, triggers, attachments, workspaces, incidents, users or agents), internal codes (status, error, cause or reason codes such as native_session_retry_exhausted or board_access_required), field or setting keys, tool names, internal process names or server file paths in a reply, even in parentheses or inline code. Say what each means in plain words instead, such as "automatic recovery gave up after 3 attempts" or "only a board user can do this". The only exceptions are link targets, values inside a command the person must run, and an ID the person explicitly asks for. +Write replies for the person, not for the API. Name each record by what the person sees in Paperclip: a task, case or approval by its identifier (such as RUN-12) or title, a person or agent by name, and link it. Name a document revision by its number as Paperclip shows it, such as revision 4, including the revision a restore or edit created. When you discuss a run, such as a failed or retried run, link it, such as [the failed run](//agents//runs/), instead of describing it without a link. Do not write raw IDs (UUIDs or their short forms for runs, revisions, handoffs, interactions, routines, triggers, attachments, workspaces, incidents, users or agents), internal codes (status, error, cause or reason codes such as native_session_retry_exhausted or board_access_required), field or setting keys, tool names, internal process names or server file paths in a reply, even in parentheses or inline code. Say what each means in plain words instead, such as "automatic recovery gave up after 3 attempts" or "only a board user can do this". The only exceptions are link targets, values inside a command the person must run, and an ID the person explicitly asks for. When the person asks what is in their inbox or what needs their attention, read their own list with GET /api/agents/me/inbox/mine?userId=, using the authorUserId of their message. Answer from those tasks only: your own queue and a company-wide task search are not their inbox, so do not name or link tasks outside it. Link each task you cite and their list as [Mine](//inbox/mine), which opens their personal Mine view in every layout; do not send them to look through an inbox page for it. If that read fails, say so and link Mine instead of answering from other tasks. diff --git a/server/src/services/routines.ts b/server/src/services/routines.ts index e12ed9432c8..b778c28e88c 100644 --- a/server/src/services/routines.ts +++ b/server/src/services/routines.ts @@ -1728,6 +1728,7 @@ export function routineService( assigneeAgentId?: string | null; idempotencyKey?: string | null; rejectIdempotencyReplay?: boolean; + replayAgentApiReceiptsFor?: string | null; routineIdempotency?: boolean; createdByRunId?: string | null; executionWorkspaceId?: string | null; @@ -1840,7 +1841,16 @@ export function routineService( and( eq(routineRuns.companyId, input.routine.companyId), eq(routineRuns.routineId, input.routine.id), - eq(routineRuns.source, input.source), + input.replayAgentApiReceiptsFor + ? or(eq(routineRuns.source, input.source), and(eq(routineRuns.source, "api"), sql`exists ( + select 1 from ${activityLog} + where ${activityLog.companyId} = ${input.routine.companyId} + and ${activityLog.entityType} = 'routine_run' + and ${activityLog.entityId} = ${routineRuns.id}::text + and ${activityLog.action} = 'routine.run_triggered' + and ${activityLog.agentId} = ${input.replayAgentApiReceiptsFor} + )`)) + : eq(routineRuns.source, input.source), eq(routineRuns.idempotencyKey, input.idempotencyKey), idempotentRunId ? eq(routineRuns.id, idempotentRunId) : input.trigger ? eq(routineRuns.triggerId, input.trigger.id) : isNull(routineRuns.triggerId), @@ -2969,6 +2979,7 @@ export function routineService( projectWorkspaceId: input.projectWorkspaceId ?? null, assigneeAgentId: input.assigneeAgentId ?? null, idempotencyKey: input.idempotencyKey, + replayAgentApiReceiptsFor: input.source === "manual" ? actor?.agentId ?? null : null, executionWorkspaceId: input.executionWorkspaceId ?? null, executionWorkspacePreference: input.executionWorkspacePreference ?? null, executionWorkspaceSettings: