Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(c): attachment pipepline

Gus9789095d81c1
diff --git a/src/daemon/src/daemon/createDaemon.ts b/src/daemon/src/daemon/createDaemon.ts
index f0ba112b9..ecaa9a14c 100644
--- a/src/daemon/src/daemon/createDaemon.ts
+++ b/src/daemon/src/daemon/createDaemon.ts
@@ -411,7 +411,7 @@ export async function createDaemon(opts: CreateDaemonOptions): Promise<RunningDa
return {
agentId,
workingDirectory: workdirFor(agentId),
- credentialProxy: { broker, proxyUrl: proxy.url, runnerKey },
+ credentialProxy: { broker, proxyUrl: proxy.url, runnerKey, capabilities: opts.capabilities },
agentCliPath: resolvedCliPath ?? opts.agentCliPath,
config: {
...(botMeta?.name ? { agentName: botMeta.name } : {}),
diff --git a/src/daemon/src/drivers/cliTransport.test.ts b/src/daemon/src/drivers/cliTransport.test.ts
index 47e8b5679..40f17510e 100644
--- a/src/daemon/src/drivers/cliTransport.test.ts
+++ b/src/daemon/src/drivers/cliTransport.test.ts
@@ -31,7 +31,7 @@ function baseCtx(workingDirectory: string, overrides: Partial<LaunchContext> = {
workingDirectory,
standingPrompt: "",
prompt: "",
- credentialProxy: { broker: broker(), proxyUrl: "http://127.0.0.1:9/proxy", runnerKey: "sk_agent_test" },
+ credentialProxy: { broker: broker(), proxyUrl: "http://127.0.0.1:9/proxy", runnerKey: "sk_agent_test", capabilities: ["send", "read"] },
config: {},
...overrides,
};
@@ -103,7 +103,7 @@ describe("prepareCliTransport — layered spawn env", () => {
// code (see plans/fix-credential-proxy-connection-leak.md).
const cred = broker();
const first = await prepareCliTransport(
- baseCtx(mkTmp(), { credentialProxy: { broker: cred, proxyUrl: "http://127.0.0.1:9/proxy", runnerKey: "sk_agent_test" } }),
+ baseCtx(mkTmp(), { credentialProxy: { broker: cred, proxyUrl: "http://127.0.0.1:9/proxy", runnerKey: "sk_agent_test", capabilities: ["send", "read"] } }),
{},
undefined,
"linux",
@@ -113,7 +113,7 @@ describe("prepareCliTransport — layered spawn env", () => {
expect(cred.check(`Bearer ${firstVoucher}`).ok).toBe(true);
const second = await prepareCliTransport(
- baseCtx(mkTmp(), { credentialProxy: { broker: cred, proxyUrl: "http://127.0.0.1:9/proxy", runnerKey: "sk_agent_test" } }),
+ baseCtx(mkTmp(), { credentialProxy: { broker: cred, proxyUrl: "http://127.0.0.1:9/proxy", runnerKey: "sk_agent_test", capabilities: ["send", "read"] } }),
{},
undefined,
"linux",
@@ -127,12 +127,32 @@ describe("prepareCliTransport — layered spawn env", () => {
expect(cred.check(`Bearer ${secondVoucher}`).ok).toBe(true);
});
+ it("mints the voucher with the capability set from the handoff", async () => {
+ const cred = broker();
+ const { tokenFile } = await prepareCliTransport(
+ baseCtx(mkTmp(), {
+ credentialProxy: {
+ broker: cred,
+ proxyUrl: "http://127.0.0.1:9/proxy",
+ runnerKey: "sk_agent_test",
+ capabilities: ["attach"],
+ },
+ }),
+ {},
+ undefined,
+ "linux",
+ );
+ const voucher = fs.readFileSync(tokenFile, "utf8");
+ expect(cred.check(`Bearer ${voucher}`, "attach").ok).toBe(true);
+ expect(cred.check(`Bearer ${voucher}`, "send").ok).toBe(false);
+ });
+
it("does not revoke a DIFFERENT agent's voucher on respawn", async () => {
const cred = broker();
await prepareCliTransport(
baseCtx(mkTmp(), {
agentId: "agent_1",
- credentialProxy: { broker: cred, proxyUrl: "http://127.0.0.1:9/proxy", runnerKey: "sk_agent_test" },
+ credentialProxy: { broker: cred, proxyUrl: "http://127.0.0.1:9/proxy", runnerKey: "sk_agent_test", capabilities: ["send", "read"] },
}),
{},
undefined,
@@ -141,7 +161,7 @@ describe("prepareCliTransport — layered spawn env", () => {
await prepareCliTransport(
baseCtx(mkTmp(), {
agentId: "agent_2",
- credentialProxy: { broker: cred, proxyUrl: "http://127.0.0.1:9/proxy", runnerKey: "sk_agent_test" },
+ credentialProxy: { broker: cred, proxyUrl: "http://127.0.0.1:9/proxy", runnerKey: "sk_agent_test", capabilities: ["send", "read"] },
}),
{},
undefined,
diff --git a/src/daemon/src/drivers/cliTransport.ts b/src/daemon/src/drivers/cliTransport.ts
index fc1a56130..0e881c3af 100644
--- a/src/daemon/src/drivers/cliTransport.ts
+++ b/src/daemon/src/drivers/cliTransport.ts
@@ -88,28 +88,10 @@ export interface CliTransportConfig {
* `cliName` won't resolve.
*/
hostCliPath?: string;
- /**
- * Capabilities granted to this launch (the host can scope them per agent).
- * Injected as `<PREFIX>_ACTIVE_CAPABILITIES` (comma-joined). Defaults to
- * `DEFAULT_ACTIVE_CAPABILITIES`.
- */
- activeCapabilities?: string[];
/** Extra static env vars the host wants every runtime to see. */
extraEnv?: Record<string, string>;
}
-/** Default capability set when a host doesn't scope one. */
-export const DEFAULT_ACTIVE_CAPABILITIES = [
- "send",
- "read",
- "mentions",
- "tasks",
- "reactions",
- "server",
- "channels",
- "knowledge",
-];
-
/**
* The default Alook CLI config template. No `hostCliPath` is wired — a real
* deployment overrides it with `{ ...DEFAULT_CLI_CONFIG, hostCliPath }`.
@@ -150,7 +132,6 @@ export async function prepareCliTransport(
): Promise<PreparedCliTransport> {
const E = cli.envPrefix;
const stateHome = resolveStateHome(E);
- const capabilities = cli.activeCapabilities ?? DEFAULT_ACTIVE_CAPABILITIES;
const stateDir = path.join(ctx.workingDirectory, cli.stateDirName);
await fs.promises.mkdir(stateDir, { recursive: true });
@@ -172,6 +153,7 @@ export async function prepareCliTransport(
"(see src/credentials) and pass { broker, proxyUrl }. There is no plaintext mode.",
);
}
+ const capabilities = ctx.credentialProxy.capabilities;
// Revoke this agent's previous voucher(s) before minting a new one — an
// agent has at most one live launch at a time, so this bounds the broker's
// registration map to "one live entry per active agent" regardless of how
diff --git a/src/daemon/src/drivers/piSdkDeps.test.ts b/src/daemon/src/drivers/piSdkDeps.test.ts
index a76404934..f9d22564c 100644
--- a/src/daemon/src/drivers/piSdkDeps.test.ts
+++ b/src/daemon/src/drivers/piSdkDeps.test.ts
@@ -28,6 +28,7 @@ function baseCtx(overrides: Partial<LaunchContext> = {}): LaunchContext {
broker: new CredentialBroker({ upstreamBaseUrl: "https://upstream.test", voucherDir: mkTmp() }),
proxyUrl: "http://127.0.0.1:9/proxy",
runnerKey: "sk_agent_test",
+ capabilities: ["send", "read"],
},
config: {},
...overrides,
diff --git a/src/daemon/src/types.ts b/src/daemon/src/types.ts
index 8b9b43ff6..d6aed73c8 100644
--- a/src/daemon/src/types.ts
+++ b/src/daemon/src/types.ts
@@ -155,6 +155,13 @@ export interface CredentialProxyHandoff {
* authed by the machine key) before spawning the agent.
*/
runnerKey: string;
+ /**
+ * Capability scope for this launch's voucher — the host owns the list and
+ * passes it in with the rest of the handoff so the driver doesn't carry a
+ * parallel default. Injected as `<PREFIX>_ACTIVE_CAPABILITIES` (comma-joined)
+ * and stamped into the voucher registration; the proxy enforces per-request.
+ */
+ capabilities: string[];
}
export interface LaunchConfig {
diff --git a/src/web/src/app/api/community/agent/send/route.test.ts b/src/web/src/app/api/community/agent/send/route.test.ts
index 2d2ad1a36..747002941 100644
--- a/src/web/src/app/api/community/agent/send/route.test.ts
+++ b/src/web/src/app/api/community/agent/send/route.test.ts
@@ -6,6 +6,7 @@ vi.mock("@opennextjs/cloudflare", () => ({
}))
vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))
+const mockFindPendingAttachmentsForBot = vi.fn(async () => [] as unknown[])
const mockFindActiveAgentRunnerKeyByBearer = vi.fn()
const mockGetUserInternal = vi.fn()
const mockGetUserByNameAndDiscriminator = vi.fn()
@@ -57,7 +58,7 @@ vi.mock("@alook/shared", async () => {
},
communityReadState: { getReadState: (...a: unknown[]) => mockGetReadState(...a) },
communityAttachment: {
- findPendingAttachmentsForBot: async () => [],
+ findPendingAttachmentsForBot: (...a: unknown[]) => mockFindPendingAttachmentsForBot(...a),
listByMessageIds: async () => [],
},
},
@@ -265,6 +266,39 @@ describe("POST /api/community/agent/send", () => {
expect(mockCreateCommunityMessage).not.toHaveBeenCalled()
})
+ it("attachment-only DM send: passes attachmentIds through to createCommunityMessage", async () => {
+ // Regression: user reported {"error":"Unexpected end of JSON input"} when
+ // running `alook message send --attachment I-... --target /.dm/peer#0001`
+ // with no `--text`. The CLI sends `content: {text: ""}` + `attachments`.
+ mockFindPendingAttachmentsForBot.mockResolvedValueOnce([
+ { id: "I-abc", uploaderId: "bot_1", kind: "dm", targetId: "dm_new" },
+ ])
+ mockGetUserByNameAndDiscriminator.mockResolvedValue({ id: "peer_1", discriminator: "0001" })
+ mockGetUserInternal.mockImplementation((_db: unknown, id: string) =>
+ Promise.resolve(id === "peer_1" ? { id: "peer_1", isBot: false, deletedAt: null } : { isBot: true, deletedAt: null })
+ )
+ mockIsBlocked.mockResolvedValue(false)
+ mockCreateOrGetDM.mockResolvedValue({ id: "dm_new" })
+ mockGetDM.mockResolvedValue({ id: "dm_new", user1Id: "bot_1", user2Id: "peer_1", lastMessageAt: null, createdAt: "t" })
+ mockCreateCommunityMessage.mockResolvedValue({
+ ok: true,
+ row: { id: "m_dm", seq: 1, content: "" },
+ attachments: [{ id: "I-abc", filename: "AGENTS.md", contentType: "text/plain", size: 7990 }],
+ })
+ const res = await POST(
+ req(
+ { channel: "/.dm/peer#0001", content: { text: "" }, attachments: ["I-abc"] },
+ { Authorization: "Bearer crk_abc" },
+ ),
+ )
+ expect(res.status).toBe(200)
+ const body = await res.json()
+ expect(body.state).toBe("sent")
+ expect(mockCreateCommunityMessage).toHaveBeenCalledWith(
+ expect.objectContaining({ attachmentIds: ["I-abc"] }),
+ )
+ })
+
it("sequential scenario: blocked/unaligned → pull+ack (simulated by an advancing lastReadSeq) → send succeeds → a new message arrives → send blocks again", async () => {
// 1. Bot is behind: latestSeq=10, bot's own tracked lastReadSeq=4 → blocked.
mockGetLatestSeqForScope.mockResolvedValueOnce(10)
diff --git a/src/web/src/lib/community/message-handler.test.ts b/src/web/src/lib/community/message-handler.test.ts
index 0ea1f2a4e..d35e323f8 100644
--- a/src/web/src/lib/community/message-handler.test.ts
+++ b/src/web/src/lib/community/message-handler.test.ts
@@ -3,6 +3,7 @@ import { describe, it, expect, vi, beforeEach } from "vitest"
const mockCreateMessage = vi.fn()
const mockGetMessage = vi.fn()
const mockGetMessageInScope = vi.fn()
+const mockHardDeleteMessage = vi.fn()
const mockGetUserInternal = vi.fn()
const mockCreateAttachment = vi.fn()
const mockReserveAttachmentsForMessage = vi.fn()
@@ -26,6 +27,7 @@ vi.mock("@alook/shared", async () => {
createMessage: (...a: unknown[]) => mockCreateMessage(...a),
getMessage: (...a: unknown[]) => mockGetMessage(...a),
getMessageInScope: (...a: unknown[]) => mockGetMessageInScope(...a),
+ hardDeleteMessage: (...a: unknown[]) => mockHardDeleteMessage(...a),
},
communityAttachment: {
createAttachment: (...a: unknown[]) => mockCreateAttachment(...a),
@@ -591,7 +593,8 @@ describe("createCommunityMessage — attachment reservation-first flow (agent pa
mockListByMessageIds.mockResolvedValue([])
})
- it("reservation-mismatch → unreserve, no message insert, generic 400", async () => {
+ it("reservation-mismatch → unreserve partial, hard-delete the orphan message, generic 400", async () => {
+ mockCreateMessage.mockResolvedValue({ id: "msg_preminted" })
mockReserveAttachmentsForMessage.mockResolvedValue(["att_1"]) // only 1 of 2 reserved
const res = await createCommunityMessage({
@@ -606,13 +609,13 @@ describe("createCommunityMessage — attachment reservation-first flow (agent pa
if (res.ok) return
expect(res.status).toBe(400)
expect(res.error).toBe("attachment not found or not attachable to this target")
+ expect(mockCreateMessage).toHaveBeenCalledTimes(1)
expect(mockUnreserveAttachments).toHaveBeenCalledWith({}, expect.objectContaining({ ids: ["att_1"] }))
- expect(mockCreateMessage).not.toHaveBeenCalled()
+ expect(mockHardDeleteMessage).toHaveBeenCalledWith({}, "msg_preminted")
expect(mockFanOutToChannel).not.toHaveBeenCalled()
})
- it("thrown insertMessageRow error → unreserve, then re-throw", async () => {
- mockReserveAttachmentsForMessage.mockResolvedValue(["att_1", "att_2"])
+ it("thrown insertMessageRow error → nothing reserved yet, no unreserve, re-throw", async () => {
mockCreateMessage.mockRejectedValue(new Error("d1_transient"))
await expect(
@@ -625,14 +628,30 @@ describe("createCommunityMessage — attachment reservation-first flow (agent pa
}),
).rejects.toThrow("d1_transient")
- expect(mockUnreserveAttachments).toHaveBeenCalledTimes(1)
- expect(mockUnreserveAttachments.mock.calls[0][1]).toEqual(
- expect.objectContaining({ ids: ["att_1", "att_2"] }),
- )
+ expect(mockReserveAttachmentsForMessage).not.toHaveBeenCalled()
+ expect(mockUnreserveAttachments).not.toHaveBeenCalled()
+ expect(mockHardDeleteMessage).not.toHaveBeenCalled()
})
- it("expectedSeq CAS-null → unreserve and return seq_conflict", async () => {
- mockReserveAttachmentsForMessage.mockResolvedValue(["att_1"])
+ it("thrown reserve error → hard-delete the just-inserted message, re-throw", async () => {
+ mockCreateMessage.mockResolvedValue({ id: "msg_preminted" })
+ mockReserveAttachmentsForMessage.mockRejectedValue(new Error("d1_transient_reserve"))
+
+ await expect(
+ createCommunityMessage({
+ db: {} as never,
+ authorId: "author_1",
+ target: { kind: "channel", channelId: "c1", serverId: "srv_1" },
+ body: { content: "hi" },
+ attachmentIds: ["att_1"],
+ }),
+ ).rejects.toThrow("d1_transient_reserve")
+
+ expect(mockHardDeleteMessage).toHaveBeenCalledWith({}, "msg_preminted")
+ expect(mockUnreserveAttachments).not.toHaveBeenCalled()
+ })
+
+ it("expectedSeq CAS-null → no reserve, no unreserve, no hardDelete, returns seq_conflict", async () => {
mockCreateMessage.mockResolvedValue(null) // CAS-null (returned, not thrown)
const res = await createCommunityMessage({
@@ -648,7 +667,9 @@ describe("createCommunityMessage — attachment reservation-first flow (agent pa
if (res.ok) return
expect(res.status).toBe(409)
expect(res.error).toBe("seq_conflict")
- expect(mockUnreserveAttachments).toHaveBeenCalledWith({}, expect.objectContaining({ ids: ["att_1"] }))
+ expect(mockReserveAttachmentsForMessage).not.toHaveBeenCalled()
+ expect(mockUnreserveAttachments).not.toHaveBeenCalled()
+ expect(mockHardDeleteMessage).not.toHaveBeenCalled()
})
it("attachment-only bot send (empty text) is NOT rejected by the empty-body guard", async () => {
diff --git a/src/web/src/lib/community/message-handler.ts b/src/web/src/lib/community/message-handler.ts
index dec0f71c5..6ba21a3bd 100644
--- a/src/web/src/lib/community/message-handler.ts
+++ b/src/web/src/lib/community/message-handler.ts
@@ -261,74 +261,66 @@ export async function createCommunityMessage(params: {
...(messageType !== undefined ? { type: messageType } : {}),
}
- // Agent-attachment path (plan §Send). Pre-mint the message id BEFORE
- // reserving pending attachments so the reservation UPDATE can point at it.
- // Reservation-first guards against unsafe rollback of
- // `insertMessageRow`'s side effects (scope counter bump, `lastMessageAt`,
- // author read-state watermark, mention/fanout).
+ // Agent-attachment path (plan §Send). `communityAttachment.messageId` is a
+ // real FK to `communityMessage.id`, so the reserve UPDATE cannot precede
+ // the message insert — D1 enforces FK checks eagerly and would reject a
+ // reserve against a not-yet-inserted pre-minted id. Insert first, then
+ // reserve; compensate with `hardDeleteMessage` if the reserve fails or
+ // partially reserves. `insertMessageRow`'s side effects (scope counter,
+ // `lastMessageAt`, author read-state) drift by one row on that rare
+ // compensating path — accepted, none of it is visible externally because
+ // WS fanout only runs on the success branch below.
const useAttachmentReservation =
attachmentIds !== undefined && attachmentIds.length > 0
const preMintedId = useAttachmentReservation ? nanoid() : undefined
- const reservedAttachmentIds: string[] = []
-
- if (useAttachmentReservation) {
- const reserved = await queries.communityAttachment.reserveAttachmentsForMessage(db, {
- ids: attachmentIds!,
- messageId: preMintedId!,
- })
- if (reserved.length !== attachmentIds!.length) {
- // Partial-overlap race (S1={A,B}, S2={B,C}). Unreserve whatever THIS
- // caller uniquely grabbed so rows aren't stuck with a message_id
- // pointing at a message that will never exist.
- await queries.communityAttachment.unreserveAttachments(db, {
- ids: reserved,
- messageId: preMintedId!,
- })
- return {
- ok: false,
- status: 400,
- error: "attachment not found or not attachable to this target",
- }
- }
- reservedAttachmentIds.push(...reserved)
- if (preMintedId) baseMessageData.id = preMintedId
- }
+ if (preMintedId) baseMessageData.id = preMintedId
// `createMessage`'s overloads key off whether the `expectedSeq` property
// is present at all, not just its runtime value — a `number | undefined`
// typed property doesn't cleanly resolve against either overload, so the
// pass-through branches explicitly instead of spreading `expectedSeq` in.
- let created: Awaited<ReturnType<typeof queries.communityMessage.createMessage>>
- try {
- created =
- expectedSeq !== undefined
- ? await queries.communityMessage.createMessage(db, { ...baseMessageData, expectedSeq })
- : await queries.communityMessage.createMessage(db, baseMessageData)
- } catch (err) {
- // D1 transient failure / batch error / FK violation: unreserve so the
- // pending rows aren't leaked. `unreserveAttachments` is scoped by
- // `messageId = preMintedId`, so it only touches rows we reserved.
- if (useAttachmentReservation) {
- await queries.communityAttachment.unreserveAttachments(db, {
- ids: reservedAttachmentIds,
- messageId: preMintedId!,
- })
- }
- throw err
- }
+ const created: Awaited<ReturnType<typeof queries.communityMessage.createMessage>> =
+ expectedSeq !== undefined
+ ? await queries.communityMessage.createMessage(db, { ...baseMessageData, expectedSeq })
+ : await queries.communityMessage.createMessage(db, baseMessageData)
// Lost the CAS race (plans/fix-agent-send-race-condition.md) — zero rows
// were written anywhere (no message, no channel/DM bump, no read-state
- // watermark). Unreserve any attachments we grabbed BEFORE returning so
- // the bot can retry with the same ids.
+ // watermark). No attachments were reserved yet, so nothing to unreserve.
if (created === null) {
- if (useAttachmentReservation) {
+ return { ok: false, status: 409, error: "seq_conflict" }
+ }
+
+ if (useAttachmentReservation) {
+ let reserved: string[]
+ try {
+ reserved = await queries.communityAttachment.reserveAttachmentsForMessage(db, {
+ ids: attachmentIds!,
+ messageId: created.id,
+ })
+ } catch (err) {
+ // Reserve threw (transient D1 / constraint / etc.). The message row
+ // exists but has zero attachments reserved to it — hard-delete it so
+ // the caller can retry with the same attachment ids.
+ await queries.communityMessage.hardDeleteMessage(db, created.id)
+ throw err
+ }
+ if (reserved.length !== attachmentIds!.length) {
+ // Partial-overlap race (S1={A,B}, S2={B,C}) or an id that no longer
+ // matches (uploader/kind/target/messageId-null). Unreserve whatever THIS
+ // caller uniquely grabbed, then hard-delete the message row so we
+ // don't leave an orphan with a partial attachment set.
await queries.communityAttachment.unreserveAttachments(db, {
- ids: reservedAttachmentIds,
- messageId: preMintedId!,
+ ids: reserved,
+ messageId: created.id,
})
+ await queries.communityMessage.hardDeleteMessage(db, created.id)
+ return {
+ ok: false,
+ status: 400,
+ error: "attachment not found or not attachable to this target",
+ }
}
- return { ok: false, status: 409, error: "seq_conflict" }
}
// Human-composer path: insert attachment rows now that the message exists.