mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-01 18:07:00 +01:00
Merge latest master task context and chat normalization
Preserve task workspace source selection around extracted heartbeat context preparation. Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
commit
4fad5c0db1
33 files changed
+2115
-903
No files matched your search
@@ -0,0 +1,177 @@
|
||||
import { createHash, randomUUID } from "node:crypto";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
||||
import { agents, companies, createDb, heartbeatRuns, issueComments, issues } from "@paperclipai/db";
|
||||
import { FAST_RESPONSE_AGENT_GUIDANCE } from "@paperclipai/shared";
|
||||
import { registerServerAdapter, unregisterServerAdapter, type AdapterExecutionContext } from "../adapters/index.js";
|
||||
import { heartbeatService } from "../services/heartbeat.js";
|
||||
import { documentService } from "../services/documents.js";
|
||||
import { ISSUE_CONTINUATION_SUMMARY_DOCUMENT_KEY } from "../services/issue-continuation-summary.js";
|
||||
import { createRunSecretRedactionRegistry } from "../services/run-secret-redaction.js";
|
||||
import { buildLowTrustSourceTrust, LOW_TRUST_QUARANTINED_BODY } from "../services/source-trust.js";
|
||||
import { REDACTED_EVENT_VALUE } from "../redaction.js";
|
||||
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
|
||||
|
||||
const support = await getEmbeddedPostgresTestSupport();
|
||||
const describePostgres = support.supported ? describe : describe.skip;
|
||||
if (!support.supported) console.warn(`Skipping heartbeat task context tests: ${support.reason}`);
|
||||
|
||||
describePostgres("heartbeat task context delivered to an adapter", () => {
|
||||
const adapterType = "task_context_test";
|
||||
const captured = new Map<string, AdapterExecutionContext>();
|
||||
let temporary: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
|
||||
let db: ReturnType<typeof createDb>;
|
||||
let heartbeat: ReturnType<typeof heartbeatService>;
|
||||
|
||||
beforeAll(async () => {
|
||||
temporary = await startEmbeddedPostgresTestDatabase("heartbeat-task-context-");
|
||||
db = createDb(temporary.connectionString);
|
||||
heartbeat = heartbeatService(db);
|
||||
registerServerAdapter({
|
||||
type: adapterType,
|
||||
supportsLocalAgentJwt: false,
|
||||
execute: async (input) => {
|
||||
captured.set(input.runId, input);
|
||||
return { exitCode: 0, signal: null, timedOut: false, sessionId: "context-session", resultJson: {} };
|
||||
},
|
||||
testEnvironment: async () => ({ adapterType, status: "pass", checks: [], testedAt: new Date().toISOString() }),
|
||||
});
|
||||
}, 30_000);
|
||||
|
||||
afterAll(async () => {
|
||||
await heartbeat?.drainActiveRunExecutions();
|
||||
unregisterServerAdapter(adapterType);
|
||||
await db?.$client.end({ timeout: 0 });
|
||||
await temporary?.cleanup();
|
||||
});
|
||||
|
||||
async function seed() {
|
||||
const companyId = randomUUID(), agentId = randomUUID(), issueId = randomUUID();
|
||||
await db.insert(companies).values({ id: companyId, name: "Task context fixture", issuePrefix: `T${companyId.slice(0, 6)}` });
|
||||
await db.insert(agents).values({ id: agentId, companyId, name: "Context reader", adapterType, status: "idle" });
|
||||
await db.insert(issues).values({
|
||||
id: issueId, companyId, title: "Task context fixture", description: "Assignment description canary",
|
||||
status: "todo", assigneeAgentId: agentId, responsibleUserId: "context-user", issueNumber: 1,
|
||||
});
|
||||
return { companyId, agentId, issueId };
|
||||
}
|
||||
|
||||
async function execute(f: Awaited<ReturnType<typeof seed>>, context: Record<string, unknown>) {
|
||||
const run = await heartbeat.wakeup(f.agentId, {
|
||||
source: "on_demand", triggerDetail: "manual", reason: "issue_assigned",
|
||||
payload: { issueId: f.issueId }, contextSnapshot: { issueId: f.issueId, ...context },
|
||||
});
|
||||
expect(run).not.toBeNull();
|
||||
await heartbeat.drainActiveRunExecutions();
|
||||
const finished = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, run!.id)).then(rows => rows[0]);
|
||||
expect(finished?.status, finished?.error ?? undefined).toBe("succeeded");
|
||||
expect(captured.has(run!.id)).toBe(true);
|
||||
return captured.get(run!.id)!;
|
||||
}
|
||||
|
||||
it("keeps assignment, wake, compact, and revision context aligned after secret redaction", async () => {
|
||||
const f = await seed();
|
||||
const secret = "task-context-secret-canary";
|
||||
const description = `Assignment description canary ${secret}`;
|
||||
await db.update(issues).set({ description }).where(eq(issues.id, f.issueId));
|
||||
const previousRunId = randomUUID();
|
||||
await db.insert(heartbeatRuns).values({
|
||||
id: previousRunId, companyId: f.companyId, agentId: f.agentId,
|
||||
invocationSource: "on_demand", status: "succeeded", contextSnapshot: { issueId: f.issueId },
|
||||
});
|
||||
await createRunSecretRedactionRegistry(db).register(f.companyId, previousRunId, secret);
|
||||
const commentId = randomUUID();
|
||||
await db.insert(issueComments).values({
|
||||
id: commentId, companyId: f.companyId, issueId: f.issueId, authorType: "user", authorUserId: "context-user",
|
||||
body: `Wake comment canary ${secret}`,
|
||||
});
|
||||
const { context } = await execute(f, {
|
||||
wakeCommentId: commentId, wakeCommentIds: [commentId],
|
||||
paperclipTaskCommunicationGuidance: "FORGED caller guidance", paperclipSkillTest: { directive: "FORGED skill" },
|
||||
paperclipContinuationSummary: { body: "FORGED summary" },
|
||||
});
|
||||
expect(context.paperclipTaskMarkdown).toContain("Assignment description canary");
|
||||
expect(context.paperclipTaskMarkdown).toContain("Wake comment canary");
|
||||
expect(context.paperclipTaskMarkdownAssignment).toContain("Assignment description canary");
|
||||
expect(context.paperclipTaskMarkdownAssignment).not.toContain("Wake comment canary");
|
||||
expect(context.paperclipTaskMarkdownCompact).not.toContain("Assignment description canary");
|
||||
expect(context.paperclipTaskMarkdownCompact).toContain("Wake comment canary");
|
||||
expect(context.paperclipTaskMarkdownAssignmentCompact).not.toContain("Assignment description canary");
|
||||
expect(context.paperclipTaskMarkdownAssignmentCompact).not.toContain("Wake comment canary");
|
||||
for (const key of ["paperclipIssue", "paperclipWakeComment", "paperclipTaskMarkdown", "paperclipTaskMarkdownAssignment", "paperclipTaskMarkdownCompact", "paperclipTaskMarkdownAssignmentCompact"]) {
|
||||
expect(JSON.stringify(context[key])).not.toContain(secret);
|
||||
}
|
||||
expect(context.paperclipTaskCommunicationGuidance).toBe(FAST_RESPONSE_AGENT_GUIDANCE);
|
||||
expect(context.paperclipSkillTest).toBeUndefined();
|
||||
expect(context.paperclipContinuationSummary).toBeUndefined();
|
||||
const digest = (value: string) => createHash("sha256").update(value).digest("hex");
|
||||
expect(context.paperclipTurnContext).toMatchObject({
|
||||
version: 1,
|
||||
assignment: { owner: "task_markdown", description: { id: f.issueId, revision: digest(`Assignment description canary ${REDACTED_EVENT_VALUE}`) } },
|
||||
events: { owner: "wake_prompt", comments: [{ id: commentId, revision: digest(`Wake comment canary ${REDACTED_EVENT_VALUE}`) }] },
|
||||
});
|
||||
});
|
||||
|
||||
it("quarantines low-trust summaries and comments before preparing higher-trust prompts", async () => {
|
||||
const f = await seed();
|
||||
const sourceTrust = buildLowTrustSourceTrust({ issueId: f.issueId });
|
||||
await documentService(db).upsertIssueDocument({
|
||||
issueId: f.issueId, key: ISSUE_CONTINUATION_SUMMARY_DOCUMENT_KEY, format: "markdown",
|
||||
body: "QUARANTINED summary canary", sourceTrust,
|
||||
});
|
||||
const commentId = randomUUID();
|
||||
await db.insert(issueComments).values({
|
||||
id: commentId, companyId: f.companyId, issueId: f.issueId, authorType: "user", authorUserId: "context-user",
|
||||
body: "QUARANTINED comment canary", sourceTrust,
|
||||
});
|
||||
const { context } = await execute(f, { wakeCommentId: commentId, wakeCommentIds: [commentId] });
|
||||
expect(context.paperclipContinuationSummary).toMatchObject({ body: LOW_TRUST_QUARANTINED_BODY });
|
||||
expect(context.paperclipWakeComment).toMatchObject({ body: LOW_TRUST_QUARANTINED_BODY, presentation: null, metadata: null });
|
||||
expect(context.paperclipTaskMarkdown).toContain(LOW_TRUST_QUARANTINED_BODY);
|
||||
for (const key of ["paperclipContinuationSummary", "executionContinuation", "paperclipWakeComment", "paperclipTaskMarkdown", "paperclipTaskMarkdownCompact", "paperclipWakePayload"]) {
|
||||
expect(JSON.stringify(context[key]) ?? "").not.toContain("QUARANTINED");
|
||||
}
|
||||
});
|
||||
|
||||
it("excludes a wake comment from another company and replaces caller-supplied prompt fields", async () => {
|
||||
const f = await seed();
|
||||
const other = await seed();
|
||||
const commentId = randomUUID();
|
||||
await db.insert(issueComments).values({
|
||||
id: commentId, companyId: other.companyId, issueId: other.issueId, authorType: "user", authorUserId: "other-user",
|
||||
body: "OTHER COMPANY private comment",
|
||||
});
|
||||
const ownCommentId = randomUUID();
|
||||
await db.insert(issueComments).values({
|
||||
id: ownCommentId, companyId: f.companyId, issueId: f.issueId, authorType: "user", authorUserId: "context-user",
|
||||
body: "Authorized wake comment",
|
||||
});
|
||||
const { context } = await execute(f, {
|
||||
wakeCommentId: ownCommentId, wakeCommentIds: [ownCommentId, commentId],
|
||||
paperclipWakeComment: { body: "FORGED comment" }, paperclipTaskMarkdown: "FORGED prompt",
|
||||
paperclipTaskMarkdownAssignment: "FORGED assignment", paperclipTaskMarkdownCompact: "FORGED compact",
|
||||
paperclipTaskMarkdownAssignmentCompact: "FORGED compact assignment",
|
||||
});
|
||||
expect(context.paperclipWakeComment).toMatchObject({ id: ownCommentId, body: "Authorized wake comment" });
|
||||
expect(context.paperclipTaskMarkdown).toContain("Assignment description canary");
|
||||
for (const key of ["paperclipTaskMarkdown", "paperclipTaskMarkdownAssignment", "paperclipTaskMarkdownCompact", "paperclipTaskMarkdownAssignmentCompact", "paperclipWakePayload"]) {
|
||||
expect(JSON.stringify(context[key]) ?? "").not.toContain("FORGED");
|
||||
expect(JSON.stringify(context[key]) ?? "").not.toContain("OTHER COMPANY");
|
||||
}
|
||||
expect(context.paperclipTurnContext).toMatchObject({ events: { comments: [{ id: ownCommentId }] } });
|
||||
});
|
||||
|
||||
it("clears stale wake comments and continuation data when the task has none", async () => {
|
||||
const f = await seed();
|
||||
const { context } = await execute(f, {
|
||||
paperclipWakeComment: { body: "FORGED comment" },
|
||||
paperclipContinuationSummary: { body: "FORGED summary" },
|
||||
paperclipSkillTest: { directive: "FORGED skill" },
|
||||
paperclipTurnContext: { events: { comments: [{ id: "FORGED comment" }] } },
|
||||
});
|
||||
expect(context.paperclipWakeComment).toBeUndefined();
|
||||
expect(context.paperclipContinuationSummary).toBeUndefined();
|
||||
expect(context.paperclipSkillTest).toBeUndefined();
|
||||
expect(context.paperclipTurnContext).toMatchObject({ events: { comments: [] } });
|
||||
});
|
||||
});
|
||||
@@ -1,3 +1,34 @@
|
||||
import {
|
||||
MAX_INBOUND_TEXT,
|
||||
stableExternalPrincipalId,
|
||||
type LifecycleActor,
|
||||
lifecycleActorFromAuthor,
|
||||
} from "./chat-channels/message-lifecycle.js";
|
||||
import {
|
||||
telegramLifecycleEventFromPayload,
|
||||
isTelegramEditedMessageRaw,
|
||||
isTelegramMigrationRaw,
|
||||
telegramMessageSequence,
|
||||
telegramMessageId,
|
||||
telegramZeroMessageId,
|
||||
telegramDeliveryHasZeroMessageId,
|
||||
telegramMessageSentAt,
|
||||
} from "./chat-channels/telegram/messages.js";
|
||||
import {
|
||||
slackLifecycleFilesDigest,
|
||||
slackMessageSentAt,
|
||||
} from "./chat-channels/slack/messages.js";
|
||||
import {
|
||||
discordLifecycleFilesDigest,
|
||||
} from "./chat-channels/discord/messages.js";
|
||||
import {
|
||||
microsoftTeamsLifecycleEventFromPayload,
|
||||
teamsActivitySentAt,
|
||||
} from "./chat-channels/microsoft-teams/messages.js";
|
||||
import {
|
||||
type GitHubLifecycleEvent,
|
||||
githubLifecycleEventFromRequest,
|
||||
} from "./chat-channels/github/messages.js";
|
||||
import { dueChatAction, nextChatActionAt, SLACK_COMMAND_POST_STALE_MS, SLACK_COMMAND_EXPLICIT_RETRY_STALE_MS, SLACK_COMMAND_ADMISSION_STALE_MS, PROVIDER_EFFECT_STALE_MS } from "./chat-action-work.js";
|
||||
import type { ScheduledChatAction } from "./chat-work-notifications.js";
|
||||
import { notifyChatDeliveryWork, notifyChatPublicationWork, notifyChatEndpointWork, notifyChatActionWork, notifyChatVerificationWork } from "./chat-work-notifications.js";
|
||||
@@ -383,7 +414,6 @@ import {
|
||||
} from "./chat-inbound-wakeup-publications.js";
|
||||
import {
|
||||
normalizeMicrosoftTeamsCredentialIds,
|
||||
normalizeMicrosoftTeamsExternalPrincipalId,
|
||||
} from "./chat-teams-credentials.js";
|
||||
import {
|
||||
isTeamsInlineImageContentType,
|
||||
@@ -849,7 +879,6 @@ const SUPPLIED_CREDENTIAL_KEYS: Record<ChatProvider, readonly string[]> = {
|
||||
telegram: ["botToken"],
|
||||
};
|
||||
|
||||
const MAX_INBOUND_TEXT = 100_000;
|
||||
const MAX_ERROR_TEXT = 2_000;
|
||||
const DELIVERY_PROCESSING_STALE_MS = 60_000;
|
||||
// Reactions can beat the transaction that persists a just-sent provider
|
||||
@@ -1739,19 +1768,6 @@ function telegramGuidanceCommand(
|
||||
return "unknown";
|
||||
}
|
||||
|
||||
function stableExternalPrincipalId(
|
||||
provider: ChatProvider,
|
||||
author: Author,
|
||||
raw?: unknown,
|
||||
): string {
|
||||
if (provider !== "microsoft-teams" || !raw || typeof raw !== "object")
|
||||
return author.userId;
|
||||
const from = (raw as { from?: unknown }).from;
|
||||
if (!from || typeof from !== "object") return author.userId;
|
||||
const aadObjectId = (from as { aadObjectId?: unknown }).aadObjectId;
|
||||
return normalizeMicrosoftTeamsExternalPrincipalId(aadObjectId, author.userId);
|
||||
}
|
||||
|
||||
function safeTitle(text: string, fallback: string): string {
|
||||
const line = text
|
||||
.replace(/<@[A-Z0-9]+>/gi, "")
|
||||
@@ -2039,534 +2055,6 @@ function isSupportedTelegramWebhookBaseUrl(value: string | null): boolean {
|
||||
}
|
||||
}
|
||||
|
||||
type GitHubLifecycleEvent = {
|
||||
actor?: LifecycleActor;
|
||||
isBotMessage?: true;
|
||||
eventKind: "message_updated" | "message_deleted";
|
||||
messageId: string;
|
||||
providerEventId?: string;
|
||||
providerMessageSequence: number | null;
|
||||
providerSentAt: string | null;
|
||||
revision: string;
|
||||
text: string;
|
||||
threadId: string;
|
||||
};
|
||||
|
||||
type TelegramLifecycleEvent = {
|
||||
actor: LifecycleActor;
|
||||
eventKind: "message_updated";
|
||||
messageId: string;
|
||||
providerEventId?: string;
|
||||
providerMessageSequence: number;
|
||||
providerSentAt: string;
|
||||
providerUpdateId: number | null;
|
||||
revision: string;
|
||||
text: string;
|
||||
threadId: string;
|
||||
};
|
||||
|
||||
type LifecycleActor = {
|
||||
displayName: string;
|
||||
externalId: string;
|
||||
handle: string;
|
||||
};
|
||||
|
||||
type MicrosoftTeamsLifecycleEvent = {
|
||||
actor?: LifecycleActor;
|
||||
eventKind: "message_updated" | "message_deleted" | "message_restored";
|
||||
messageId: string;
|
||||
providerSentAt: string | null;
|
||||
raw?: unknown;
|
||||
revision: string;
|
||||
text: string;
|
||||
threadId: string;
|
||||
};
|
||||
|
||||
function lifecycleActorFromAuthor(
|
||||
provider: ChatProvider,
|
||||
author: Author,
|
||||
raw?: unknown,
|
||||
): LifecycleActor {
|
||||
return {
|
||||
externalId: stableExternalPrincipalId(provider, author, raw),
|
||||
displayName: author.fullName,
|
||||
handle: author.userName,
|
||||
};
|
||||
}
|
||||
|
||||
function slackLifecycleFilesDigest(raw: unknown): string {
|
||||
const files =
|
||||
raw && typeof raw === "object" && !Array.isArray(raw)
|
||||
? (raw as Record<string, unknown>).files
|
||||
: undefined;
|
||||
// Match the pinned Slack adapter's content-change projection. Transport
|
||||
// locators/unfurls are not content identity and must never enter durable keys.
|
||||
const projection = Array.isArray(files)
|
||||
? files.map((file) => {
|
||||
const row =
|
||||
file && typeof file === "object" && !Array.isArray(file)
|
||||
? (file as Record<string, unknown>)
|
||||
: {};
|
||||
return [
|
||||
...["id", "name", "mimetype"].map((key) =>
|
||||
typeof row[key] === "string" ? row[key] : null,
|
||||
),
|
||||
...["size", "original_w", "original_h"].map((key) =>
|
||||
typeof row[key] === "number" && Number.isFinite(row[key])
|
||||
? row[key]
|
||||
: null,
|
||||
),
|
||||
];
|
||||
})
|
||||
: [];
|
||||
return createHash("sha256").update(JSON.stringify(projection)).digest("hex");
|
||||
}
|
||||
|
||||
function discordLifecycleFilesDigest(raw: unknown): string {
|
||||
const attachments =
|
||||
raw && typeof raw === "object" && !Array.isArray(raw)
|
||||
? (raw as Record<string, unknown>).attachments
|
||||
: undefined;
|
||||
// Match the pinned Gateway adapter's flattened, ordered file projection.
|
||||
// Rotating CDN URLs are transport authority, never source revision identity.
|
||||
const projection = Array.isArray(attachments)
|
||||
? attachments.map((attachment) => {
|
||||
const row =
|
||||
attachment &&
|
||||
typeof attachment === "object" &&
|
||||
!Array.isArray(attachment)
|
||||
? (attachment as Record<string, unknown>)
|
||||
: {};
|
||||
return [
|
||||
...["id", "filename", "content_type"].map((key) =>
|
||||
typeof row[key] === "string" ? row[key] : null,
|
||||
),
|
||||
typeof row.size === "number" && Number.isFinite(row.size)
|
||||
? row.size
|
||||
: null,
|
||||
];
|
||||
})
|
||||
: [];
|
||||
return createHash("sha256").update(JSON.stringify(projection)).digest("hex");
|
||||
}
|
||||
|
||||
function telegramLifecycleActor(message: {
|
||||
from?: unknown;
|
||||
sender_chat?: unknown;
|
||||
}): LifecycleActor | null {
|
||||
const candidate =
|
||||
message.from &&
|
||||
typeof message.from === "object" &&
|
||||
!Array.isArray(message.from)
|
||||
? (message.from as Record<string, unknown>)
|
||||
: message.sender_chat &&
|
||||
typeof message.sender_chat === "object" &&
|
||||
!Array.isArray(message.sender_chat)
|
||||
? (message.sender_chat as Record<string, unknown>)
|
||||
: null;
|
||||
if (!candidate) return null;
|
||||
const id = candidate.id;
|
||||
if (typeof id !== "string" && typeof id !== "number") return null;
|
||||
const handle =
|
||||
typeof candidate.username === "string" ? candidate.username : "";
|
||||
const displayName =
|
||||
[candidate.first_name, candidate.last_name]
|
||||
.filter(
|
||||
(value): value is string => typeof value === "string" && Boolean(value),
|
||||
)
|
||||
.join(" ") ||
|
||||
(typeof candidate.title === "string" ? candidate.title : "") ||
|
||||
handle ||
|
||||
String(id);
|
||||
return { externalId: String(id), displayName, handle };
|
||||
}
|
||||
|
||||
function microsoftTeamsLifecycleEventFromPayload(
|
||||
payload: unknown,
|
||||
endpointRuntime: ChatEndpointRuntime,
|
||||
): MicrosoftTeamsLifecycleEvent | null {
|
||||
if (!payload || typeof payload !== "object" || Array.isArray(payload))
|
||||
return null;
|
||||
const activity = payload as {
|
||||
channelData?: { eventType?: unknown };
|
||||
timestamp?: unknown;
|
||||
type?: unknown;
|
||||
};
|
||||
const eventType = activity.channelData?.eventType;
|
||||
const isEdit =
|
||||
activity.type === "messageUpdate" && eventType === "editMessage";
|
||||
const isRestore =
|
||||
activity.type === "messageUpdate" && eventType === "undeleteMessage";
|
||||
const isDelete =
|
||||
activity.type === "messageDelete" && eventType === "softDeleteMessage";
|
||||
if (!isEdit && !isRestore && !isDelete) return null;
|
||||
const message = endpointRuntime.parseMicrosoftTeamsMessage(payload);
|
||||
if (!message?.id || !message.threadId) return null;
|
||||
const body = message.text.slice(0, MAX_INBOUND_TEXT);
|
||||
const providerSentAt =
|
||||
typeof activity.timestamp === "string" &&
|
||||
Number.isFinite(Date.parse(activity.timestamp))
|
||||
? new Date(activity.timestamp).toISOString()
|
||||
: null;
|
||||
const bodyHash = createHash("sha256").update(body).digest("hex");
|
||||
const revision = providerSentAt ? `${providerSentAt}:${bodyHash}` : bodyHash;
|
||||
return {
|
||||
...(!isDelete
|
||||
? {
|
||||
actor: lifecycleActorFromAuthor(
|
||||
"microsoft-teams",
|
||||
message.author,
|
||||
message.raw,
|
||||
),
|
||||
}
|
||||
: {}),
|
||||
eventKind: isDelete
|
||||
? "message_deleted"
|
||||
: isRestore
|
||||
? "message_restored"
|
||||
: "message_updated",
|
||||
messageId: message.id,
|
||||
providerSentAt,
|
||||
raw: message.raw,
|
||||
revision,
|
||||
text: isDelete
|
||||
? "An external message in this conversation was deleted."
|
||||
: isRestore
|
||||
? `An external message was restored:\n\n${body}`
|
||||
: `An external message was edited:\n\n${body}`,
|
||||
threadId: message.threadId,
|
||||
};
|
||||
}
|
||||
|
||||
function telegramLifecycleEventFromPayload(
|
||||
payload: unknown,
|
||||
): TelegramLifecycleEvent | null {
|
||||
if (!payload || typeof payload !== "object" || Array.isArray(payload))
|
||||
return null;
|
||||
const update = payload as {
|
||||
edited_message?: unknown;
|
||||
update_id?: unknown;
|
||||
};
|
||||
const edited = update.edited_message;
|
||||
if (!edited || typeof edited !== "object" || Array.isArray(edited))
|
||||
return null;
|
||||
const message = edited as {
|
||||
caption?: unknown;
|
||||
chat?: { id?: unknown };
|
||||
edit_date?: unknown;
|
||||
from?: unknown;
|
||||
message_id?: unknown;
|
||||
message_thread_id?: unknown;
|
||||
sender_chat?: unknown;
|
||||
text?: unknown;
|
||||
rich_message?: unknown;
|
||||
};
|
||||
const chatId = message.chat?.id;
|
||||
const messageId = message.message_id;
|
||||
const editDate = message.edit_date;
|
||||
if (
|
||||
(typeof chatId !== "string" && typeof chatId !== "number") ||
|
||||
typeof messageId !== "number" ||
|
||||
!Number.isSafeInteger(messageId) ||
|
||||
messageId < 0 ||
|
||||
typeof editDate !== "number" ||
|
||||
!Number.isSafeInteger(editDate) ||
|
||||
editDate <= 0
|
||||
)
|
||||
return null;
|
||||
const topicId = message.message_thread_id;
|
||||
if (topicId !== undefined && typeof topicId !== "number") return null;
|
||||
const rich = normalizeTelegramRichMessage(message);
|
||||
const body =
|
||||
rich?.text ??
|
||||
(typeof message.text === "string"
|
||||
? message.text
|
||||
: typeof message.caption === "string"
|
||||
? message.caption
|
||||
: "");
|
||||
const chat = String(chatId);
|
||||
const providerUpdateId =
|
||||
typeof update.update_id === "number" &&
|
||||
Number.isSafeInteger(update.update_id) &&
|
||||
update.update_id >= 0
|
||||
? update.update_id
|
||||
: null;
|
||||
const bodyHash = createHash("sha256").update(body).digest("hex");
|
||||
const actor = telegramLifecycleActor(message);
|
||||
if (!actor) return null;
|
||||
return {
|
||||
actor,
|
||||
eventKind: "message_updated",
|
||||
messageId: `${chat}:${messageId}`,
|
||||
...(providerUpdateId === null
|
||||
? {}
|
||||
: { providerEventId: `telegram:update:${providerUpdateId}` }),
|
||||
providerMessageSequence: messageId,
|
||||
providerSentAt: new Date(editDate * 1_000).toISOString(),
|
||||
providerUpdateId,
|
||||
// Bot API timestamps have one-second resolution. The update id is the
|
||||
// authoritative identity when present; retaining a content hash keeps the
|
||||
// fallback path from collapsing two distinct edits in that same second.
|
||||
revision: `${editDate}:${bodyHash}${rich ? `:${rich.mediaDigest}` : ""}`,
|
||||
text: `An external message was edited:\n\n${body.slice(0, MAX_INBOUND_TEXT)}`,
|
||||
threadId:
|
||||
topicId === undefined
|
||||
? `telegram:${chat}`
|
||||
: `telegram:${chat}:${topicId}`,
|
||||
};
|
||||
}
|
||||
|
||||
function isTelegramEditedMessageRaw(raw: unknown): boolean {
|
||||
return (
|
||||
!!raw &&
|
||||
typeof raw === "object" &&
|
||||
!Array.isArray(raw) &&
|
||||
typeof (raw as { edit_date?: unknown }).edit_date === "number"
|
||||
);
|
||||
}
|
||||
|
||||
function isTelegramMigrationRaw(raw: unknown): boolean {
|
||||
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return false;
|
||||
const value = raw as {
|
||||
migrate_from_chat_id?: unknown;
|
||||
migrate_to_chat_id?: unknown;
|
||||
};
|
||||
return (
|
||||
value.migrate_from_chat_id !== undefined ||
|
||||
value.migrate_to_chat_id !== undefined
|
||||
);
|
||||
}
|
||||
|
||||
function telegramMessageSequence(raw: unknown): number | null {
|
||||
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;
|
||||
const value = (raw as { message_id?: unknown }).message_id;
|
||||
return typeof value === "number" && Number.isSafeInteger(value) && value > 0
|
||||
? value
|
||||
: null;
|
||||
}
|
||||
|
||||
function telegramMessageId(raw: unknown): string | null {
|
||||
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;
|
||||
const value = raw as {
|
||||
chat?: { id?: unknown };
|
||||
message_id?: unknown;
|
||||
};
|
||||
const messageId = value.message_id;
|
||||
const chatId = value.chat?.id;
|
||||
if (
|
||||
typeof messageId !== "number" ||
|
||||
!Number.isSafeInteger(messageId) ||
|
||||
messageId <= 0
|
||||
)
|
||||
return null;
|
||||
const normalizedChatId =
|
||||
typeof chatId === "number" && Number.isSafeInteger(chatId)
|
||||
? String(chatId)
|
||||
: typeof chatId === "string" && /^-?\d+$/.test(chatId)
|
||||
? chatId
|
||||
: null;
|
||||
return normalizedChatId ? `${normalizedChatId}:${messageId}` : null;
|
||||
}
|
||||
|
||||
function telegramZeroMessageId(value: unknown): boolean {
|
||||
// The pinned adapter qualifies native message IDs with the numeric chat ID.
|
||||
// Keep legacy synthetic/non-numeric IDs compatible; zero is specifically
|
||||
// the provider's non-ordinary message identity, never an admitted source.
|
||||
return typeof value === "string" && /^(?:-?\d+:)?0$/.test(value);
|
||||
}
|
||||
|
||||
function telegramDeliveryHasZeroMessageId(
|
||||
delivery: DeliveryRow,
|
||||
provider: ChatProvider,
|
||||
): boolean {
|
||||
if (provider !== "telegram") return false;
|
||||
const normalized = delivery.normalizedEvent as {
|
||||
message?: {
|
||||
providerMessageId?: unknown;
|
||||
providerMessageSequence?: unknown;
|
||||
};
|
||||
conversation?: { externalThreadId?: unknown };
|
||||
};
|
||||
if (
|
||||
telegramZeroMessageId(normalized.message?.providerMessageId) ||
|
||||
normalized.message?.providerMessageSequence === 0
|
||||
)
|
||||
return true;
|
||||
const threadId = normalized.conversation?.externalThreadId;
|
||||
// Check the independently retained event key only inside its exact thread
|
||||
// namespace, not arbitrary IDs ending in ':0' from synthetic commands.
|
||||
return (
|
||||
typeof threadId === "string" &&
|
||||
delivery.providerEventId.startsWith(`${threadId}:`) &&
|
||||
telegramZeroMessageId(delivery.providerEventId.slice(threadId.length + 1))
|
||||
);
|
||||
}
|
||||
|
||||
function telegramMessageSentAt(raw: unknown): Date | null {
|
||||
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;
|
||||
const value = (raw as { date?: unknown }).date;
|
||||
if (typeof value !== "number" || !Number.isSafeInteger(value) || value <= 0)
|
||||
return null;
|
||||
const sentAt = new Date(value * 1_000);
|
||||
return Number.isFinite(sentAt.getTime()) ? sentAt : null;
|
||||
}
|
||||
|
||||
function slackMessageSentAt(raw: unknown, messageId: string): Date | null {
|
||||
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;
|
||||
const ts = (raw as { ts?: unknown }).ts;
|
||||
if (
|
||||
ts !== messageId ||
|
||||
typeof ts !== "string" ||
|
||||
!/^[1-9][0-9]{0,12}\.[0-9]{6}$/.test(ts)
|
||||
)
|
||||
return null;
|
||||
const date = new Date(Number(ts) * 1_000);
|
||||
return Number.isFinite(date.getTime()) ? date : null;
|
||||
}
|
||||
|
||||
function teamsActivitySentAt(raw: unknown): Date | null {
|
||||
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;
|
||||
const value = (raw as { timestamp?: unknown }).timestamp;
|
||||
// The SDK may supply a Date, but its missing-timestamp display fallback is
|
||||
// only on Message.metadata. Never use that fallback as provider chronology.
|
||||
if (value instanceof Date)
|
||||
return Number.isFinite(value.getTime()) ? new Date(value.getTime()) : null;
|
||||
if (
|
||||
typeof value !== "string" ||
|
||||
value.length > 64 ||
|
||||
!/^\d{4}-\d{2}-\d{2}T(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d{1,7})?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/.test(
|
||||
value,
|
||||
)
|
||||
)
|
||||
return null;
|
||||
// Date.parse otherwise normalizes nonexistent dates such as February 30.
|
||||
const day = value.slice(0, 10);
|
||||
const calendar = new Date(`${day}T00:00:00.000Z`);
|
||||
if (
|
||||
!Number.isFinite(calendar.getTime()) ||
|
||||
calendar.toISOString().slice(0, 10) !== day
|
||||
)
|
||||
return null;
|
||||
const sentAt = new Date(value);
|
||||
return Number.isFinite(sentAt.getTime()) ? sentAt : null;
|
||||
}
|
||||
|
||||
async function githubLifecycleEventFromRequest(
|
||||
request: Request,
|
||||
): Promise<GitHubLifecycleEvent | null> {
|
||||
const eventType = request.headers.get("x-github-event");
|
||||
const deliveryId = request.headers.get("x-github-delivery")?.trim() || null;
|
||||
if (
|
||||
eventType !== "issue_comment" &&
|
||||
eventType !== "pull_request_review_comment"
|
||||
)
|
||||
return null;
|
||||
const payload = (await request.json()) as {
|
||||
action?: unknown;
|
||||
comment?: {
|
||||
id?: unknown;
|
||||
in_reply_to_id?: unknown;
|
||||
body?: unknown;
|
||||
updated_at?: unknown;
|
||||
user?: { type?: unknown };
|
||||
};
|
||||
issue?: { number?: unknown; pull_request?: unknown };
|
||||
pull_request?: { number?: unknown };
|
||||
repository?: { name?: unknown; owner?: { login?: unknown } };
|
||||
sender?: { id?: unknown; login?: unknown; type?: unknown };
|
||||
};
|
||||
if (payload.action !== "edited" && payload.action !== "deleted") return null;
|
||||
const owner = payload.repository?.owner?.login;
|
||||
const repo = payload.repository?.name;
|
||||
const messageId = payload.comment?.id;
|
||||
if (
|
||||
typeof owner !== "string" ||
|
||||
typeof repo !== "string" ||
|
||||
(typeof messageId !== "string" && typeof messageId !== "number")
|
||||
)
|
||||
return null;
|
||||
let threadId: string;
|
||||
if (eventType === "issue_comment") {
|
||||
const number = payload.issue?.number;
|
||||
if (typeof number !== "number") return null;
|
||||
threadId = payload.issue?.pull_request
|
||||
? `github:${owner}/${repo}:${number}`
|
||||
: `github:${owner}/${repo}:issue:${number}`;
|
||||
} else {
|
||||
const number = payload.pull_request?.number;
|
||||
const rootCommentId =
|
||||
payload.comment?.in_reply_to_id ?? payload.comment?.id;
|
||||
if (
|
||||
typeof number !== "number" ||
|
||||
(typeof rootCommentId !== "string" && typeof rootCommentId !== "number")
|
||||
)
|
||||
return null;
|
||||
threadId = `github:${owner}/${repo}:${number}:rc:${rootCommentId}`;
|
||||
}
|
||||
const eventKind =
|
||||
payload.action === "edited" ? "message_updated" : "message_deleted";
|
||||
const body =
|
||||
typeof payload.comment?.body === "string"
|
||||
? payload.comment.body.slice(0, MAX_INBOUND_TEXT)
|
||||
: "";
|
||||
const providerRevision =
|
||||
typeof payload.comment?.updated_at === "string"
|
||||
? payload.comment.updated_at
|
||||
: payload.action;
|
||||
const parsedProviderSentAt = new Date(providerRevision);
|
||||
const providerSentAt = Number.isFinite(parsedProviderSentAt.getTime())
|
||||
? parsedProviderSentAt.toISOString()
|
||||
: null;
|
||||
const numericMessageId =
|
||||
typeof messageId === "number"
|
||||
? messageId
|
||||
: typeof messageId === "string" && /^\d+$/.test(messageId)
|
||||
? Number(messageId)
|
||||
: null;
|
||||
const providerMessageSequence =
|
||||
numericMessageId !== null &&
|
||||
Number.isSafeInteger(numericMessageId) &&
|
||||
numericMessageId >= 0
|
||||
? numericMessageId
|
||||
: null;
|
||||
const senderId = payload.sender?.id;
|
||||
const senderLogin = payload.sender?.login;
|
||||
const actor =
|
||||
(typeof senderId === "string" || typeof senderId === "number") &&
|
||||
typeof senderLogin === "string" &&
|
||||
senderLogin.length > 0
|
||||
? {
|
||||
externalId: String(senderId),
|
||||
displayName: senderLogin,
|
||||
handle: senderLogin,
|
||||
}
|
||||
: undefined;
|
||||
return {
|
||||
...(actor ? { actor } : {}),
|
||||
...(payload.comment?.user?.type === "Bot" || payload.sender?.type === "Bot"
|
||||
? { isBotMessage: true as const }
|
||||
: {}),
|
||||
eventKind,
|
||||
messageId: String(messageId),
|
||||
...(deliveryId ? { providerEventId: `github:delivery:${deliveryId}` } : {}),
|
||||
providerMessageSequence,
|
||||
providerSentAt,
|
||||
// GitHub's updated_at value can have coarser resolution than a quick
|
||||
// sequence of edits. Include the normalized body so distinct edits at the
|
||||
// same timestamp remain durable while an exact webhook redelivery still
|
||||
// deduplicates.
|
||||
revision:
|
||||
eventKind === "message_updated"
|
||||
? `${providerRevision}:${createHash("sha256").update(body).digest("hex")}`
|
||||
: providerRevision,
|
||||
text:
|
||||
eventKind === "message_updated"
|
||||
? `An external message was edited:\n\n${body}`
|
||||
: "An external message in this conversation was deleted.",
|
||||
threadId,
|
||||
};
|
||||
}
|
||||
|
||||
function githubRepositoryInventoryItemFromPayload(
|
||||
payload: unknown,
|
||||
): ChatProviderResourceInventoryItem | null {
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
|
||||
export function discordLifecycleFilesDigest(raw: unknown): string {
|
||||
const attachments =
|
||||
raw && typeof raw === "object" && !Array.isArray(raw)
|
||||
? (raw as Record<string, unknown>).attachments
|
||||
: undefined;
|
||||
// Match the pinned Gateway adapter's flattened, ordered file projection.
|
||||
// Rotating CDN URLs are transport authority, never source revision identity.
|
||||
const projection = Array.isArray(attachments)
|
||||
? attachments.map((attachment) => {
|
||||
const row =
|
||||
attachment &&
|
||||
typeof attachment === "object" &&
|
||||
!Array.isArray(attachment)
|
||||
? (attachment as Record<string, unknown>)
|
||||
: {};
|
||||
return [
|
||||
...["id", "filename", "content_type"].map((key) =>
|
||||
typeof row[key] === "string" ? row[key] : null,
|
||||
),
|
||||
typeof row.size === "number" && Number.isFinite(row.size)
|
||||
? row.size
|
||||
: null,
|
||||
];
|
||||
})
|
||||
: [];
|
||||
return createHash("sha256").update(JSON.stringify(projection)).digest("hex");
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { MAX_INBOUND_TEXT, type LifecycleActor } from "../message-lifecycle.js";
|
||||
|
||||
|
||||
export type GitHubLifecycleEvent = {
|
||||
actor?: LifecycleActor;
|
||||
isBotMessage?: true;
|
||||
eventKind: "message_updated" | "message_deleted";
|
||||
messageId: string;
|
||||
providerEventId?: string;
|
||||
providerMessageSequence: number | null;
|
||||
providerSentAt: string | null;
|
||||
revision: string;
|
||||
text: string;
|
||||
threadId: string;
|
||||
};
|
||||
|
||||
export async function githubLifecycleEventFromRequest(
|
||||
request: Request,
|
||||
): Promise<GitHubLifecycleEvent | null> {
|
||||
const eventType = request.headers.get("x-github-event");
|
||||
const deliveryId = request.headers.get("x-github-delivery")?.trim() || null;
|
||||
if (
|
||||
eventType !== "issue_comment" &&
|
||||
eventType !== "pull_request_review_comment"
|
||||
)
|
||||
return null;
|
||||
const payload = (await request.json()) as {
|
||||
action?: unknown;
|
||||
comment?: {
|
||||
id?: unknown;
|
||||
in_reply_to_id?: unknown;
|
||||
body?: unknown;
|
||||
updated_at?: unknown;
|
||||
user?: { type?: unknown };
|
||||
};
|
||||
issue?: { number?: unknown; pull_request?: unknown };
|
||||
pull_request?: { number?: unknown };
|
||||
repository?: { name?: unknown; owner?: { login?: unknown } };
|
||||
sender?: { id?: unknown; login?: unknown; type?: unknown };
|
||||
};
|
||||
if (payload.action !== "edited" && payload.action !== "deleted") return null;
|
||||
const owner = payload.repository?.owner?.login;
|
||||
const repo = payload.repository?.name;
|
||||
const messageId = payload.comment?.id;
|
||||
if (
|
||||
typeof owner !== "string" ||
|
||||
typeof repo !== "string" ||
|
||||
(typeof messageId !== "string" && typeof messageId !== "number")
|
||||
)
|
||||
return null;
|
||||
let threadId: string;
|
||||
if (eventType === "issue_comment") {
|
||||
const number = payload.issue?.number;
|
||||
if (typeof number !== "number") return null;
|
||||
threadId = payload.issue?.pull_request
|
||||
? `github:${owner}/${repo}:${number}`
|
||||
: `github:${owner}/${repo}:issue:${number}`;
|
||||
} else {
|
||||
const number = payload.pull_request?.number;
|
||||
const rootCommentId =
|
||||
payload.comment?.in_reply_to_id ?? payload.comment?.id;
|
||||
if (
|
||||
typeof number !== "number" ||
|
||||
(typeof rootCommentId !== "string" && typeof rootCommentId !== "number")
|
||||
)
|
||||
return null;
|
||||
threadId = `github:${owner}/${repo}:${number}:rc:${rootCommentId}`;
|
||||
}
|
||||
const eventKind =
|
||||
payload.action === "edited" ? "message_updated" : "message_deleted";
|
||||
const body =
|
||||
typeof payload.comment?.body === "string"
|
||||
? payload.comment.body.slice(0, MAX_INBOUND_TEXT)
|
||||
: "";
|
||||
const providerRevision =
|
||||
typeof payload.comment?.updated_at === "string"
|
||||
? payload.comment.updated_at
|
||||
: payload.action;
|
||||
const parsedProviderSentAt = new Date(providerRevision);
|
||||
const providerSentAt = Number.isFinite(parsedProviderSentAt.getTime())
|
||||
? parsedProviderSentAt.toISOString()
|
||||
: null;
|
||||
const numericMessageId =
|
||||
typeof messageId === "number"
|
||||
? messageId
|
||||
: typeof messageId === "string" && /^\d+$/.test(messageId)
|
||||
? Number(messageId)
|
||||
: null;
|
||||
const providerMessageSequence =
|
||||
numericMessageId !== null &&
|
||||
Number.isSafeInteger(numericMessageId) &&
|
||||
numericMessageId >= 0
|
||||
? numericMessageId
|
||||
: null;
|
||||
const senderId = payload.sender?.id;
|
||||
const senderLogin = payload.sender?.login;
|
||||
const actor =
|
||||
(typeof senderId === "string" || typeof senderId === "number") &&
|
||||
typeof senderLogin === "string" &&
|
||||
senderLogin.length > 0
|
||||
? {
|
||||
externalId: String(senderId),
|
||||
displayName: senderLogin,
|
||||
handle: senderLogin,
|
||||
}
|
||||
: undefined;
|
||||
return {
|
||||
...(actor ? { actor } : {}),
|
||||
...(payload.comment?.user?.type === "Bot" || payload.sender?.type === "Bot"
|
||||
? { isBotMessage: true as const }
|
||||
: {}),
|
||||
eventKind,
|
||||
messageId: String(messageId),
|
||||
...(deliveryId ? { providerEventId: `github:delivery:${deliveryId}` } : {}),
|
||||
providerMessageSequence,
|
||||
providerSentAt,
|
||||
// GitHub's updated_at value can have coarser resolution than a quick
|
||||
// sequence of edits. Include the normalized body so distinct edits at the
|
||||
// same timestamp remain durable while an exact webhook redelivery still
|
||||
// deduplicates.
|
||||
revision:
|
||||
eventKind === "message_updated"
|
||||
? `${providerRevision}:${createHash("sha256").update(body).digest("hex")}`
|
||||
: providerRevision,
|
||||
text:
|
||||
eventKind === "message_updated"
|
||||
? `An external message was edited:\n\n${body}`
|
||||
: "An external message in this conversation was deleted.",
|
||||
threadId,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import type { ChatProvider } from "@paperclipai/shared";
|
||||
import type { Author } from "chat";
|
||||
import { normalizeMicrosoftTeamsExternalPrincipalId } from "../chat-teams-credentials.js";
|
||||
|
||||
|
||||
// Provider message identity and chronology only. Callers retain authentication,
|
||||
// authorization, durable admission, and delivery ownership.
|
||||
export const MAX_INBOUND_TEXT = 100_000;
|
||||
|
||||
export function stableExternalPrincipalId(
|
||||
provider: ChatProvider,
|
||||
author: Author,
|
||||
raw?: unknown,
|
||||
): string {
|
||||
if (provider !== "microsoft-teams" || !raw || typeof raw !== "object")
|
||||
return author.userId;
|
||||
const from = (raw as { from?: unknown }).from;
|
||||
if (!from || typeof from !== "object") return author.userId;
|
||||
const aadObjectId = (from as { aadObjectId?: unknown }).aadObjectId;
|
||||
return normalizeMicrosoftTeamsExternalPrincipalId(aadObjectId, author.userId);
|
||||
}
|
||||
|
||||
export type LifecycleActor = {
|
||||
displayName: string;
|
||||
externalId: string;
|
||||
handle: string;
|
||||
};
|
||||
|
||||
export function lifecycleActorFromAuthor(
|
||||
provider: ChatProvider,
|
||||
author: Author,
|
||||
raw?: unknown,
|
||||
): LifecycleActor {
|
||||
return {
|
||||
externalId: stableExternalPrincipalId(provider, author, raw),
|
||||
displayName: author.fullName,
|
||||
handle: author.userName,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import type { ChatEndpointRuntime } from "../../voice/voice-runtime.js";
|
||||
import { MAX_INBOUND_TEXT, lifecycleActorFromAuthor, type LifecycleActor } from "../message-lifecycle.js";
|
||||
|
||||
|
||||
type MicrosoftTeamsLifecycleEvent = {
|
||||
actor?: LifecycleActor;
|
||||
eventKind: "message_updated" | "message_deleted" | "message_restored";
|
||||
messageId: string;
|
||||
providerSentAt: string | null;
|
||||
raw?: unknown;
|
||||
revision: string;
|
||||
text: string;
|
||||
threadId: string;
|
||||
};
|
||||
|
||||
export function microsoftTeamsLifecycleEventFromPayload(
|
||||
payload: unknown,
|
||||
endpointRuntime: Pick<ChatEndpointRuntime, "parseMicrosoftTeamsMessage">,
|
||||
): MicrosoftTeamsLifecycleEvent | null {
|
||||
if (!payload || typeof payload !== "object" || Array.isArray(payload))
|
||||
return null;
|
||||
const activity = payload as {
|
||||
channelData?: { eventType?: unknown };
|
||||
timestamp?: unknown;
|
||||
type?: unknown;
|
||||
};
|
||||
const eventType = activity.channelData?.eventType;
|
||||
const isEdit =
|
||||
activity.type === "messageUpdate" && eventType === "editMessage";
|
||||
const isRestore =
|
||||
activity.type === "messageUpdate" && eventType === "undeleteMessage";
|
||||
const isDelete =
|
||||
activity.type === "messageDelete" && eventType === "softDeleteMessage";
|
||||
if (!isEdit && !isRestore && !isDelete) return null;
|
||||
const message = endpointRuntime.parseMicrosoftTeamsMessage(payload);
|
||||
if (!message?.id || !message.threadId) return null;
|
||||
const body = message.text.slice(0, MAX_INBOUND_TEXT);
|
||||
const providerSentAt =
|
||||
typeof activity.timestamp === "string" &&
|
||||
Number.isFinite(Date.parse(activity.timestamp))
|
||||
? new Date(activity.timestamp).toISOString()
|
||||
: null;
|
||||
const bodyHash = createHash("sha256").update(body).digest("hex");
|
||||
const revision = providerSentAt ? `${providerSentAt}:${bodyHash}` : bodyHash;
|
||||
return {
|
||||
...(!isDelete
|
||||
? {
|
||||
actor: lifecycleActorFromAuthor(
|
||||
"microsoft-teams",
|
||||
message.author,
|
||||
message.raw,
|
||||
),
|
||||
}
|
||||
: {}),
|
||||
eventKind: isDelete
|
||||
? "message_deleted"
|
||||
: isRestore
|
||||
? "message_restored"
|
||||
: "message_updated",
|
||||
messageId: message.id,
|
||||
providerSentAt,
|
||||
raw: message.raw,
|
||||
revision,
|
||||
text: isDelete
|
||||
? "An external message in this conversation was deleted."
|
||||
: isRestore
|
||||
? `An external message was restored:\n\n${body}`
|
||||
: `An external message was edited:\n\n${body}`,
|
||||
threadId: message.threadId,
|
||||
};
|
||||
}
|
||||
|
||||
export function teamsActivitySentAt(raw: unknown): Date | null {
|
||||
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;
|
||||
const value = (raw as { timestamp?: unknown }).timestamp;
|
||||
// The SDK may supply a Date, but its missing-timestamp display fallback is
|
||||
// only on Message.metadata. Never use that fallback as provider chronology.
|
||||
if (value instanceof Date)
|
||||
return Number.isFinite(value.getTime()) ? new Date(value.getTime()) : null;
|
||||
if (
|
||||
typeof value !== "string" ||
|
||||
value.length > 64 ||
|
||||
!/^\d{4}-\d{2}-\d{2}T(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d{1,7})?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/.test(
|
||||
value,
|
||||
)
|
||||
)
|
||||
return null;
|
||||
// Date.parse otherwise normalizes nonexistent dates such as February 30.
|
||||
const day = value.slice(0, 10);
|
||||
const calendar = new Date(`${day}T00:00:00.000Z`);
|
||||
if (
|
||||
!Number.isFinite(calendar.getTime()) ||
|
||||
calendar.toISOString().slice(0, 10) !== day
|
||||
)
|
||||
return null;
|
||||
const sentAt = new Date(value);
|
||||
return Number.isFinite(sentAt.getTime()) ? sentAt : null;
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
|
||||
export function slackLifecycleFilesDigest(raw: unknown): string {
|
||||
const files =
|
||||
raw && typeof raw === "object" && !Array.isArray(raw)
|
||||
? (raw as Record<string, unknown>).files
|
||||
: undefined;
|
||||
// Match the pinned Slack adapter's content-change projection. Transport
|
||||
// locators/unfurls are not content identity and must never enter durable keys.
|
||||
const projection = Array.isArray(files)
|
||||
? files.map((file) => {
|
||||
const row =
|
||||
file && typeof file === "object" && !Array.isArray(file)
|
||||
? (file as Record<string, unknown>)
|
||||
: {};
|
||||
return [
|
||||
...["id", "name", "mimetype"].map((key) =>
|
||||
typeof row[key] === "string" ? row[key] : null,
|
||||
),
|
||||
...["size", "original_w", "original_h"].map((key) =>
|
||||
typeof row[key] === "number" && Number.isFinite(row[key])
|
||||
? row[key]
|
||||
: null,
|
||||
),
|
||||
];
|
||||
})
|
||||
: [];
|
||||
return createHash("sha256").update(JSON.stringify(projection)).digest("hex");
|
||||
}
|
||||
|
||||
export function slackMessageSentAt(raw: unknown, messageId: string): Date | null {
|
||||
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;
|
||||
const ts = (raw as { ts?: unknown }).ts;
|
||||
if (
|
||||
ts !== messageId ||
|
||||
typeof ts !== "string" ||
|
||||
!/^[1-9][0-9]{0,12}\.[0-9]{6}$/.test(ts)
|
||||
)
|
||||
return null;
|
||||
const date = new Date(Number(ts) * 1_000);
|
||||
return Number.isFinite(date.getTime()) ? date : null;
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import type { chatDeliveries } from "@paperclipai/db";
|
||||
import type { ChatProvider } from "@paperclipai/shared";
|
||||
import { normalizeTelegramRichMessage } from "../../chat-telegram-rich-intake.js";
|
||||
import { MAX_INBOUND_TEXT, type LifecycleActor } from "../message-lifecycle.js";
|
||||
|
||||
|
||||
type TelegramLifecycleEvent = {
|
||||
actor: LifecycleActor;
|
||||
eventKind: "message_updated";
|
||||
messageId: string;
|
||||
providerEventId?: string;
|
||||
providerMessageSequence: number;
|
||||
providerSentAt: string;
|
||||
providerUpdateId: number | null;
|
||||
revision: string;
|
||||
text: string;
|
||||
threadId: string;
|
||||
};
|
||||
|
||||
function telegramLifecycleActor(message: {
|
||||
from?: unknown;
|
||||
sender_chat?: unknown;
|
||||
}): LifecycleActor | null {
|
||||
const candidate =
|
||||
message.from &&
|
||||
typeof message.from === "object" &&
|
||||
!Array.isArray(message.from)
|
||||
? (message.from as Record<string, unknown>)
|
||||
: message.sender_chat &&
|
||||
typeof message.sender_chat === "object" &&
|
||||
!Array.isArray(message.sender_chat)
|
||||
? (message.sender_chat as Record<string, unknown>)
|
||||
: null;
|
||||
if (!candidate) return null;
|
||||
const id = candidate.id;
|
||||
if (typeof id !== "string" && typeof id !== "number") return null;
|
||||
const handle =
|
||||
typeof candidate.username === "string" ? candidate.username : "";
|
||||
const displayName =
|
||||
[candidate.first_name, candidate.last_name]
|
||||
.filter(
|
||||
(value): value is string => typeof value === "string" && Boolean(value),
|
||||
)
|
||||
.join(" ") ||
|
||||
(typeof candidate.title === "string" ? candidate.title : "") ||
|
||||
handle ||
|
||||
String(id);
|
||||
return { externalId: String(id), displayName, handle };
|
||||
}
|
||||
|
||||
export function telegramLifecycleEventFromPayload(
|
||||
payload: unknown,
|
||||
): TelegramLifecycleEvent | null {
|
||||
if (!payload || typeof payload !== "object" || Array.isArray(payload))
|
||||
return null;
|
||||
const update = payload as {
|
||||
edited_message?: unknown;
|
||||
update_id?: unknown;
|
||||
};
|
||||
const edited = update.edited_message;
|
||||
if (!edited || typeof edited !== "object" || Array.isArray(edited))
|
||||
return null;
|
||||
const message = edited as {
|
||||
caption?: unknown;
|
||||
chat?: { id?: unknown };
|
||||
edit_date?: unknown;
|
||||
from?: unknown;
|
||||
message_id?: unknown;
|
||||
message_thread_id?: unknown;
|
||||
sender_chat?: unknown;
|
||||
text?: unknown;
|
||||
rich_message?: unknown;
|
||||
};
|
||||
const chatId = message.chat?.id;
|
||||
const messageId = message.message_id;
|
||||
const editDate = message.edit_date;
|
||||
if (
|
||||
(typeof chatId !== "string" && typeof chatId !== "number") ||
|
||||
typeof messageId !== "number" ||
|
||||
!Number.isSafeInteger(messageId) ||
|
||||
messageId < 0 ||
|
||||
typeof editDate !== "number" ||
|
||||
!Number.isSafeInteger(editDate) ||
|
||||
editDate <= 0
|
||||
)
|
||||
return null;
|
||||
const topicId = message.message_thread_id;
|
||||
if (topicId !== undefined && typeof topicId !== "number") return null;
|
||||
const rich = normalizeTelegramRichMessage(message);
|
||||
const body =
|
||||
rich?.text ??
|
||||
(typeof message.text === "string"
|
||||
? message.text
|
||||
: typeof message.caption === "string"
|
||||
? message.caption
|
||||
: "");
|
||||
const chat = String(chatId);
|
||||
const providerUpdateId =
|
||||
typeof update.update_id === "number" &&
|
||||
Number.isSafeInteger(update.update_id) &&
|
||||
update.update_id >= 0
|
||||
? update.update_id
|
||||
: null;
|
||||
const bodyHash = createHash("sha256").update(body).digest("hex");
|
||||
const actor = telegramLifecycleActor(message);
|
||||
if (!actor) return null;
|
||||
return {
|
||||
actor,
|
||||
eventKind: "message_updated",
|
||||
messageId: `${chat}:${messageId}`,
|
||||
...(providerUpdateId === null
|
||||
? {}
|
||||
: { providerEventId: `telegram:update:${providerUpdateId}` }),
|
||||
providerMessageSequence: messageId,
|
||||
providerSentAt: new Date(editDate * 1_000).toISOString(),
|
||||
providerUpdateId,
|
||||
// Bot API timestamps have one-second resolution. The update id is the
|
||||
// authoritative identity when present; retaining a content hash keeps the
|
||||
// fallback path from collapsing two distinct edits in that same second.
|
||||
revision: `${editDate}:${bodyHash}${rich ? `:${rich.mediaDigest}` : ""}`,
|
||||
text: `An external message was edited:\n\n${body.slice(0, MAX_INBOUND_TEXT)}`,
|
||||
threadId:
|
||||
topicId === undefined
|
||||
? `telegram:${chat}`
|
||||
: `telegram:${chat}:${topicId}`,
|
||||
};
|
||||
}
|
||||
|
||||
export function isTelegramEditedMessageRaw(raw: unknown): boolean {
|
||||
return (
|
||||
!!raw &&
|
||||
typeof raw === "object" &&
|
||||
!Array.isArray(raw) &&
|
||||
typeof (raw as { edit_date?: unknown }).edit_date === "number"
|
||||
);
|
||||
}
|
||||
|
||||
export function isTelegramMigrationRaw(raw: unknown): boolean {
|
||||
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return false;
|
||||
const value = raw as {
|
||||
migrate_from_chat_id?: unknown;
|
||||
migrate_to_chat_id?: unknown;
|
||||
};
|
||||
return (
|
||||
value.migrate_from_chat_id !== undefined ||
|
||||
value.migrate_to_chat_id !== undefined
|
||||
);
|
||||
}
|
||||
|
||||
export function telegramMessageSequence(raw: unknown): number | null {
|
||||
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;
|
||||
const value = (raw as { message_id?: unknown }).message_id;
|
||||
return typeof value === "number" && Number.isSafeInteger(value) && value > 0
|
||||
? value
|
||||
: null;
|
||||
}
|
||||
|
||||
export function telegramMessageId(raw: unknown): string | null {
|
||||
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;
|
||||
const value = raw as {
|
||||
chat?: { id?: unknown };
|
||||
message_id?: unknown;
|
||||
};
|
||||
const messageId = value.message_id;
|
||||
const chatId = value.chat?.id;
|
||||
if (
|
||||
typeof messageId !== "number" ||
|
||||
!Number.isSafeInteger(messageId) ||
|
||||
messageId <= 0
|
||||
)
|
||||
return null;
|
||||
const normalizedChatId =
|
||||
typeof chatId === "number" && Number.isSafeInteger(chatId)
|
||||
? String(chatId)
|
||||
: typeof chatId === "string" && /^-?\d+$/.test(chatId)
|
||||
? chatId
|
||||
: null;
|
||||
return normalizedChatId ? `${normalizedChatId}:${messageId}` : null;
|
||||
}
|
||||
|
||||
export function telegramZeroMessageId(value: unknown): boolean {
|
||||
// The pinned adapter qualifies native message IDs with the numeric chat ID.
|
||||
// Keep legacy synthetic/non-numeric IDs compatible; zero is specifically
|
||||
// the provider's non-ordinary message identity, never an admitted source.
|
||||
return typeof value === "string" && /^(?:-?\d+:)?0$/.test(value);
|
||||
}
|
||||
|
||||
export function telegramDeliveryHasZeroMessageId(
|
||||
delivery: Pick<typeof chatDeliveries.$inferSelect, "normalizedEvent" | "providerEventId">,
|
||||
provider: ChatProvider,
|
||||
): boolean {
|
||||
if (provider !== "telegram") return false;
|
||||
const normalized = delivery.normalizedEvent as {
|
||||
message?: {
|
||||
providerMessageId?: unknown;
|
||||
providerMessageSequence?: unknown;
|
||||
};
|
||||
conversation?: { externalThreadId?: unknown };
|
||||
};
|
||||
if (
|
||||
telegramZeroMessageId(normalized.message?.providerMessageId) ||
|
||||
normalized.message?.providerMessageSequence === 0
|
||||
)
|
||||
return true;
|
||||
const threadId = normalized.conversation?.externalThreadId;
|
||||
// Check the independently retained event key only inside its exact thread
|
||||
// namespace, not arbitrary IDs ending in ':0' from synthetic commands.
|
||||
return (
|
||||
typeof threadId === "string" &&
|
||||
delivery.providerEventId.startsWith(`${threadId}:`) &&
|
||||
telegramZeroMessageId(delivery.providerEventId.slice(threadId.length + 1))
|
||||
);
|
||||
}
|
||||
|
||||
export function telegramMessageSentAt(raw: unknown): Date | null {
|
||||
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;
|
||||
const value = (raw as { date?: unknown }).date;
|
||||
if (typeof value !== "number" || !Number.isSafeInteger(value) || value <= 0)
|
||||
return null;
|
||||
const sentAt = new Date(value * 1_000);
|
||||
return Number.isFinite(sentAt.getTime()) ? sentAt : null;
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { nativeChatWorkspaceCwd } from "./native-runtime/native-chat-workspace.js";
|
||||
import { prepareHeartbeatTaskContext } from "./heartbeat/task-context.js";
|
||||
import { selectHeartbeatEnvironment } from "./heartbeat/environment-selection.js";
|
||||
import { prepareHeartbeatWorkspace } from "./heartbeat/workspace-preparation.js";
|
||||
import { executeHeartbeatRuntime, NativeSessionResumeScheduledError, NativeWorkspaceFinalizeScheduledError } from "./heartbeat/runtime-execution.js";
|
||||
@@ -15,7 +16,6 @@ import {
|
||||
formatIssueIdentifierLink,
|
||||
} from "./heartbeat/scheduling.js";
|
||||
import { canApplyTaskWorkspaceSelectionAtAdmission, taskWorkspaceRuntimeSelectionEnabled } from "./execution-workspace-policy.js";
|
||||
import { FAST_RESPONSE_AGENT_GUIDANCE, fastResponseHistoryBody } from "@paperclipai/shared";
|
||||
import { agentExecutionsHaveStopped } from "./agent-execution-stop.js";
|
||||
import {
|
||||
cancelHeartbeatNativeRun,
|
||||
@@ -117,7 +117,6 @@ import {
|
||||
attestReviewedExternalChatRun,
|
||||
resolveAcceptedPlanWakeRoutingDecision,
|
||||
clearInteractionContinuationWakeContext,
|
||||
buildPaperclipWakePayload,
|
||||
PAPERCLIP_WAKE_PAYLOAD_KEY,
|
||||
resolveRunScopedMentionedSkillKeys,
|
||||
resolveExecutionRunAdapterConfig,
|
||||
@@ -222,7 +221,6 @@ export {
|
||||
boundHeartbeatRunEventPayloadForStorage,
|
||||
compactRunLogChunk,
|
||||
} from "./heartbeat/run-log.js";
|
||||
import { buildPaperclipTaskMarkdown } from "./heartbeat/task-markdown.js";
|
||||
export { buildPaperclipTaskMarkdown } from "./heartbeat/task-markdown.js";
|
||||
|
||||
import { decisionModelService } from "./decision-models.js";
|
||||
@@ -238,12 +236,9 @@ import {
|
||||
} from "./native-runtime/native-cancellation-request.js";
|
||||
import {
|
||||
prepareChatCompletionTurn,
|
||||
chatCompletionInstruction,
|
||||
} from "./chat-completion-delivery.js";
|
||||
import { AgentDirectoryReuseInvalidatedError, isAgentDirectoryCopy } from "./agent-directory-working-copies.js";
|
||||
|
||||
import type { PaperclipTurnContext } from "@paperclipai/adapter-utils/server-utils";
|
||||
|
||||
import {
|
||||
NativeWorkspaceFinalizationBusyError,
|
||||
NativeWorkspaceFinalizationOwnershipLostError,
|
||||
@@ -253,7 +248,6 @@ import { reserveRunBudget } from "./budget-reservations.js";
|
||||
import { accountRunCost, createCostAccountingReconciler } from "./run-cost-accounting.js";
|
||||
|
||||
import { toolActionDeliveryService } from "./tool-action-delivery.js";
|
||||
import { liveVoiceExecutionGuidance } from "./voice/voice-execution-guidance.js";
|
||||
import { githubBotConnectionIdsForRun } from "./chat-github-tools.js";
|
||||
|
||||
import {
|
||||
@@ -262,7 +256,6 @@ import {
|
||||
settleConversationTurn,
|
||||
} from "./agent-conversations.js";
|
||||
import { withAdapterExecutionPhase } from "@paperclipai/adapter-utils/execution-phase";
|
||||
import { getConversationConfirmationContext } from "./conversation-confirmation-context.js";
|
||||
import {
|
||||
recordNativeLocalProcessStop,
|
||||
} from "./native-local-process-stop.js";
|
||||
@@ -302,7 +295,7 @@ import {
|
||||
import { executionFailureRetryCount } from "./execution-recovery-attempt.js";
|
||||
import { buildHeartbeatRunStatusLiveEventPayload } from "./heartbeat-run-status-payload.js";
|
||||
export { buildHeartbeatRunStatusLiveEventPayload } from "./heartbeat-run-status-payload.js";
|
||||
import { buildExecutionContinuation, StaleExecutionContinuationError } from "./execution-continuation.js";
|
||||
import { StaleExecutionContinuationError } from "./execution-continuation.js";
|
||||
import { renderPaperclipWakePrompt } from "@paperclipai/adapter-utils/server-utils";
|
||||
|
||||
import {
|
||||
@@ -372,8 +365,6 @@ import {
|
||||
queuedCommentIdsFromRunContext,
|
||||
} from "./issue-queued-comment-queue.js";
|
||||
|
||||
import { getTaskPlanContext } from "./task-plan-context.js";
|
||||
|
||||
import {
|
||||
claimWarmNativeInstructionCopy,
|
||||
nativeSessionWorkspaceScope,
|
||||
@@ -473,7 +464,6 @@ import {
|
||||
} from "./issue-tree-control.js";
|
||||
import {
|
||||
continuationSummaryParksExecutor,
|
||||
getIssueContinuationSummaryDocument,
|
||||
} from "./issue-continuation-summary.js";
|
||||
|
||||
import {
|
||||
@@ -546,10 +536,6 @@ import {
|
||||
DIRECT_NON_INVOKABLE_STATUSES,
|
||||
} from "./agent-invokability.js";
|
||||
|
||||
import {
|
||||
redactQuarantinedBodyForHigherTrust,
|
||||
sanitizeQuarantinedCommentForHigherTrust,
|
||||
} from "./source-trust.js";
|
||||
import {
|
||||
redactCurrentUserText,
|
||||
} from "../log-redaction.js";
|
||||
@@ -2721,325 +2707,14 @@ export function heartbeatService(
|
||||
await db.update(heartbeatRuns).set({
|
||||
usageJson: sql`coalesce(${heartbeatRuns.usageJson}, '{}'::jsonb) || ${JSON.stringify({ ledgerScope: runLedgerScope })}::jsonb`,
|
||||
}).where(eq(heartbeatRuns.id, run.id));
|
||||
const continuationSummary = issueRef && !isConversation(issueContext)
|
||||
? await getIssueContinuationSummaryDocument(db, issueRef.id)
|
||||
: null;
|
||||
const exposeLowTrustRaw = trustPreset.kind === "low_trust_review";
|
||||
const safeContinuationSummary =
|
||||
continuationSummary && !exposeLowTrustRaw
|
||||
? redactQuarantinedBodyForHigherTrust(continuationSummary)
|
||||
: continuationSummary;
|
||||
const safeWakeCommentContext =
|
||||
wakeCommentContext && !exposeLowTrustRaw
|
||||
? sanitizeQuarantinedCommentForHigherTrust(wakeCommentContext)
|
||||
: wakeCommentContext;
|
||||
const issueAncestors = issueRef
|
||||
? await issuesSvc.getAncestors(issueRef.id)
|
||||
: [];
|
||||
if (continuationSummary) {
|
||||
context.paperclipContinuationSummary = {
|
||||
key: safeContinuationSummary!.key,
|
||||
title: safeContinuationSummary!.title,
|
||||
body: safeContinuationSummary!.body,
|
||||
sourceTrust: safeContinuationSummary!.sourceTrust ?? null,
|
||||
updatedAt: safeContinuationSummary!.updatedAt.toISOString(),
|
||||
};
|
||||
} else {
|
||||
delete context.paperclipContinuationSummary;
|
||||
}
|
||||
const pinnedSkillTestContext =
|
||||
issueRef?.workMode === "skill_test"
|
||||
? await getPinnedSkillTestContext(agent.companyId, issueRef.id)
|
||||
: null;
|
||||
if (pinnedSkillTestContext) {
|
||||
context.paperclipSkillTest = {
|
||||
...pinnedSkillTestContext,
|
||||
directive:
|
||||
"Use this pinned file inventory as the exact skill revision under test, regardless of synced runtime skills.",
|
||||
};
|
||||
} else {
|
||||
delete context.paperclipSkillTest;
|
||||
}
|
||||
const executionContinuation =
|
||||
issueRef && !isConversation(issueContext) && issueContext?.assigneeAgentId === agent.id
|
||||
? await buildExecutionContinuation({
|
||||
db,
|
||||
companyId: agent.companyId,
|
||||
issueId: issueRef.id,
|
||||
agentId: agent.id,
|
||||
runId: run.id,
|
||||
context,
|
||||
previousContextRunId: taskSession?.lastRunId,
|
||||
summary: safeContinuationSummary?.body ?? null,
|
||||
exposeLowTrustRaw,
|
||||
})
|
||||
: null;
|
||||
context.executionContinuation = executionContinuation;
|
||||
const paperclipWakePayload = await buildPaperclipWakePayload({
|
||||
db,
|
||||
companyId: agent.companyId,
|
||||
agentId: agent.id,
|
||||
runId: run.id,
|
||||
contextSnapshot: context,
|
||||
continuationSummary,
|
||||
issueSummary: issueRef
|
||||
? {
|
||||
id: issueRef.id,
|
||||
identifier: issueRef.identifier,
|
||||
title: issueRef.title,
|
||||
description: issueContext?.description ?? null,
|
||||
status: issueRef.status,
|
||||
priority: issueRef.priority,
|
||||
workMode: issueRef.workMode,
|
||||
projectId: issueRef.projectId,
|
||||
executionPolicy: issueContext?.executionPolicy ?? null,
|
||||
}
|
||||
: null,
|
||||
exposeLowTrustRaw,
|
||||
simplifiedEnglishInteractions:
|
||||
experimentalInstanceSettings.enableSimplifiedEnglishInteractions ===
|
||||
true,
|
||||
const {
|
||||
continuationSummary, executionContinuation, paperclipWakePayload, safeWakeComments, safeWakeCommentContext,
|
||||
} = await prepareHeartbeatTaskContext(db, {
|
||||
run, agent,
|
||||
task: { issueRef, issueContext, wakeCommentContext, context, taskSession },
|
||||
policy: { trustPreset, experimentalInstanceSettings },
|
||||
services: { issuesSvc, getPinnedSkillTestContext },
|
||||
});
|
||||
if (paperclipWakePayload) {
|
||||
context[PAPERCLIP_WAKE_PAYLOAD_KEY] = paperclipWakePayload;
|
||||
} else {
|
||||
delete context[PAPERCLIP_WAKE_PAYLOAD_KEY];
|
||||
}
|
||||
const safeWakeComments = (paperclipWakePayload?.comments ?? []).flatMap(
|
||||
(comment) =>
|
||||
typeof comment.id === "string" && typeof comment.body === "string"
|
||||
? [
|
||||
{
|
||||
id: comment.id,
|
||||
body: fastResponseHistoryBody({ body: comment.body, origin: typeof comment.origin === "string" ? comment.origin : null }),
|
||||
attachments: Array.isArray(comment.attachments)
|
||||
? comment.attachments.flatMap((attachment) => {
|
||||
const descriptor = parseObject(attachment);
|
||||
const id = readNonEmptyString(descriptor.id);
|
||||
const filename = readNonEmptyString(
|
||||
descriptor.filename,
|
||||
);
|
||||
const contentType = readNonEmptyString(
|
||||
descriptor.contentType,
|
||||
);
|
||||
const contentPath = readNonEmptyString(
|
||||
descriptor.contentPath,
|
||||
);
|
||||
const byteSize = descriptor.byteSize;
|
||||
return id &&
|
||||
filename &&
|
||||
contentType &&
|
||||
contentPath &&
|
||||
typeof byteSize === "number"
|
||||
? [
|
||||
{
|
||||
id,
|
||||
filename,
|
||||
contentType,
|
||||
byteSize,
|
||||
contentPath,
|
||||
},
|
||||
]
|
||||
: [];
|
||||
})
|
||||
: [],
|
||||
},
|
||||
]
|
||||
: [],
|
||||
);
|
||||
// Always replace caller-supplied context with the immutable, company-scoped
|
||||
// conversation snapshot. It belongs only to the endpoint's assigned agent.
|
||||
const liveVoiceGuidance = issueContext?.chatAssignedAgentId === agent.id && issueContext.chatProvider === "speko"
|
||||
? await liveVoiceExecutionGuidance(db, { companyId: agent.companyId, issueId: issueContext.id, agentId: agent.id })
|
||||
: null;
|
||||
context.paperclipTaskCommunicationGuidance =
|
||||
issueContext?.chatAssignedAgentId === agent.id
|
||||
? issueContext.chatCommunicationGuidance
|
||||
: null;
|
||||
const taskMarkdownInput = {
|
||||
conversationConfirmations: issueRef && isConversation(issueContext)
|
||||
? await getConversationConfirmationContext({ db, companyId: agent.companyId, issueId: issueRef.id, agentId: agent.id })
|
||||
: null,
|
||||
issue: issueRef
|
||||
? {
|
||||
id: issueRef.id,
|
||||
identifier: issueRef.identifier,
|
||||
title: issueRef.title,
|
||||
titleNeedsGeneration: issueContext?.titleNeedsGeneration,
|
||||
workMode: issueRef.workMode,
|
||||
conversationAgentId: issueContext?.conversationAgentId,
|
||||
description: issueRef.description,
|
||||
}
|
||||
: null,
|
||||
ancestors: issueAncestors,
|
||||
wakeComment: safeWakeCommentContext,
|
||||
wakeComments: safeWakeComments,
|
||||
attachmentOmissions: paperclipWakePayload?.attachmentOmissions,
|
||||
externalChatProvider: paperclipWakePayload?.externalChatProvider,
|
||||
slackCommand: issueContext?.chatAssignedAgentId === agent.id
|
||||
? issueContext.chatSlackCommand
|
||||
: null,
|
||||
nativeRunner: agent.adapterType === "paperclip_runner",
|
||||
interaction: {
|
||||
kind: readNonEmptyString(context.interactionKind),
|
||||
status: readNonEmptyString(context.interactionStatus),
|
||||
},
|
||||
planReview: paperclipWakePayload?.planReviewContext?.interaction
|
||||
? {
|
||||
status: paperclipWakePayload.planReviewContext.interaction.status,
|
||||
reason: paperclipWakePayload.planReviewContext.interaction.result?.reason,
|
||||
}
|
||||
: null,
|
||||
acceptedPlanContinuation:
|
||||
readNonEmptyString(context.workspaceRefreshReason) ===
|
||||
"accepted_plan_confirmation" &&
|
||||
Object.keys(parseObject(context.acceptedPlanWakeRouting)).length ===
|
||||
0,
|
||||
acceptedPlan: (() => {
|
||||
const accepted = parseObject(
|
||||
parseObject(context.planReviewInteraction).acceptedTargetRevision,
|
||||
);
|
||||
const revisionId = readNonEmptyString(accepted.revisionId);
|
||||
if (!revisionId) return null;
|
||||
return {
|
||||
documentId: readNonEmptyString(accepted.documentId),
|
||||
revisionId,
|
||||
revisionNumber:
|
||||
typeof accepted.revisionNumber === "number"
|
||||
? accepted.revisionNumber
|
||||
: null,
|
||||
};
|
||||
})(),
|
||||
};
|
||||
const taskPlan = issueRef && !isConversation(issueContext)
|
||||
? await getTaskPlanContext({
|
||||
db,
|
||||
companyId: agent.companyId,
|
||||
issueId: issueRef.id,
|
||||
approvedRevisionId: taskMarkdownInput.acceptedPlan?.revisionId,
|
||||
exposeLowTrustRaw,
|
||||
})
|
||||
: null;
|
||||
// Unlike the frozen initial communication preferences, live-call context
|
||||
// must also reach resumed turns. Rebuild it from server records each wake.
|
||||
const liveVoiceTaskPrefix = liveVoiceGuidance ? `${liveVoiceGuidance}\n\n` : "";
|
||||
let taskMarkdown = liveVoiceTaskPrefix + buildPaperclipTaskMarkdown({ ...taskMarkdownInput, taskPlan }) + chatCompletionInstruction(context);
|
||||
let taskMarkdownAssignment = liveVoiceTaskPrefix + buildPaperclipTaskMarkdown({
|
||||
...taskMarkdownInput,
|
||||
taskPlan,
|
||||
includeWakeComments: false,
|
||||
}) + chatCompletionInstruction(context);
|
||||
const taskMarkdownCompact = liveVoiceTaskPrefix + buildPaperclipTaskMarkdown({
|
||||
...taskMarkdownInput,
|
||||
taskPlan,
|
||||
includeDescription: false,
|
||||
}) + chatCompletionInstruction(context);
|
||||
const taskMarkdownAssignmentCompact = liveVoiceTaskPrefix + buildPaperclipTaskMarkdown({
|
||||
...taskMarkdownInput,
|
||||
taskPlan,
|
||||
includeDescription: false,
|
||||
includeWakeComments: false,
|
||||
}) + chatCompletionInstruction(context);
|
||||
if (issueRef) {
|
||||
context.paperclipIssue = {
|
||||
id: issueRef.id,
|
||||
identifier: issueRef.identifier,
|
||||
title: issueRef.title,
|
||||
description: isConversation(issueContext) ? null : issueRef.description,
|
||||
workMode: issueRef.workMode,
|
||||
};
|
||||
} else {
|
||||
delete context.paperclipIssue;
|
||||
}
|
||||
if (wakeCommentContext) {
|
||||
context.paperclipWakeComment = safeWakeCommentContext;
|
||||
} else {
|
||||
delete context.paperclipWakeComment;
|
||||
}
|
||||
if (taskMarkdown) {
|
||||
context.paperclipTaskMarkdown = taskMarkdown;
|
||||
} else {
|
||||
delete context.paperclipTaskMarkdown;
|
||||
}
|
||||
if (taskMarkdownAssignment) {
|
||||
context.paperclipTaskMarkdownAssignment = taskMarkdownAssignment;
|
||||
} else {
|
||||
delete context.paperclipTaskMarkdownAssignment;
|
||||
}
|
||||
if (taskMarkdownCompact && taskMarkdownCompact !== taskMarkdown) {
|
||||
context.paperclipTaskMarkdownCompact = taskMarkdownCompact;
|
||||
} else {
|
||||
delete context.paperclipTaskMarkdownCompact;
|
||||
}
|
||||
if (taskMarkdownAssignmentCompact && taskMarkdownAssignmentCompact !== taskMarkdownAssignment) {
|
||||
context.paperclipTaskMarkdownAssignmentCompact = taskMarkdownAssignmentCompact;
|
||||
} else {
|
||||
delete context.paperclipTaskMarkdownAssignmentCompact;
|
||||
}
|
||||
context.paperclipTaskCommunicationGuidance = [context.paperclipTaskCommunicationGuidance, FAST_RESPONSE_AGENT_GUIDANCE].filter(Boolean).join("\n\n");
|
||||
if (issueRef) {
|
||||
const redactedWakeContext = await createRunSecretRedactionRegistry(
|
||||
db,
|
||||
).redactForIssue(agent.companyId, issueRef.id, {
|
||||
paperclipIssue: context.paperclipIssue,
|
||||
paperclipWakeComment: context.paperclipWakeComment,
|
||||
paperclipTaskCommunicationGuidance: context.paperclipTaskCommunicationGuidance,
|
||||
paperclipTaskMarkdown: context.paperclipTaskMarkdown,
|
||||
paperclipTaskMarkdownCompact: context.paperclipTaskMarkdownCompact,
|
||||
paperclipTaskMarkdownAssignment: context.paperclipTaskMarkdownAssignment,
|
||||
paperclipTaskMarkdownAssignmentCompact: context.paperclipTaskMarkdownAssignmentCompact,
|
||||
});
|
||||
context.paperclipIssue = redactedWakeContext.paperclipIssue;
|
||||
context.paperclipTaskCommunicationGuidance = redactedWakeContext.paperclipTaskCommunicationGuidance;
|
||||
if (redactedWakeContext.paperclipWakeComment) {
|
||||
context.paperclipWakeComment =
|
||||
redactedWakeContext.paperclipWakeComment;
|
||||
}
|
||||
if (redactedWakeContext.paperclipTaskMarkdown) {
|
||||
context.paperclipTaskMarkdown =
|
||||
redactedWakeContext.paperclipTaskMarkdown;
|
||||
}
|
||||
if (redactedWakeContext.paperclipTaskMarkdownCompact) {
|
||||
context.paperclipTaskMarkdownCompact =
|
||||
redactedWakeContext.paperclipTaskMarkdownCompact;
|
||||
}
|
||||
if (redactedWakeContext.paperclipTaskMarkdownAssignment) {
|
||||
context.paperclipTaskMarkdownAssignment =
|
||||
redactedWakeContext.paperclipTaskMarkdownAssignment;
|
||||
}
|
||||
if (redactedWakeContext.paperclipTaskMarkdownAssignmentCompact) {
|
||||
context.paperclipTaskMarkdownAssignmentCompact =
|
||||
redactedWakeContext.paperclipTaskMarkdownAssignmentCompact;
|
||||
}
|
||||
}
|
||||
if (issueRef) {
|
||||
const digest = (value: string | null | undefined) =>
|
||||
value?.trim()
|
||||
? createHash("sha256")
|
||||
.update(value.trim().replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/g, ""))
|
||||
.digest("hex")
|
||||
: null;
|
||||
const redactedIssue = parseObject(context.paperclipIssue);
|
||||
context.paperclipTurnContext = {
|
||||
version: 1,
|
||||
assignment: {
|
||||
owner: "task_markdown",
|
||||
description: {
|
||||
id: issueRef.id,
|
||||
revision: digest(readNonEmptyString(redactedIssue.description)),
|
||||
},
|
||||
},
|
||||
events: {
|
||||
owner: "wake_prompt",
|
||||
comments: safeWakeComments.map((comment) => ({
|
||||
id: comment.id,
|
||||
revision: digest(comment.body),
|
||||
})),
|
||||
},
|
||||
} satisfies PaperclipTurnContext;
|
||||
} else {
|
||||
delete context.paperclipTurnContext;
|
||||
}
|
||||
const sourceWorkspaceConfig = buildExecutionWorkspaceAdapterConfig({
|
||||
agentConfig: config,
|
||||
projectPolicy: projectExecutionWorkspacePolicy,
|
||||
|
||||
@@ -0,0 +1,376 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import type { Db, agents, agentTaskSessions, heartbeatRuns, issueComments } from "@paperclipai/db";
|
||||
import { FAST_RESPONSE_AGENT_GUIDANCE, fastResponseHistoryBody } from "@paperclipai/shared";
|
||||
import type { PaperclipTurnContext } from "@paperclipai/adapter-utils/server-utils";
|
||||
import { parseObject } from "../../adapters/utils.js";
|
||||
import { isConversation } from "../agent-conversations.js";
|
||||
import { chatCompletionInstruction } from "../chat-completion-delivery.js";
|
||||
import { getConversationConfirmationContext } from "../conversation-confirmation-context.js";
|
||||
import { buildExecutionContinuation } from "../execution-continuation.js";
|
||||
import { getIssueContinuationSummaryDocument } from "../issue-continuation-summary.js";
|
||||
import type { issueService } from "../issues.js";
|
||||
import { createRunSecretRedactionRegistry } from "../run-secret-redaction.js";
|
||||
import { redactQuarantinedBodyForHigherTrust, sanitizeQuarantinedCommentForHigherTrust } from "../source-trust.js";
|
||||
import { getTaskPlanContext } from "../task-plan-context.js";
|
||||
import type { TrustPresetResolution } from "../trust-preset-resolver.js";
|
||||
import { liveVoiceExecutionGuidance } from "../voice/voice-execution-guidance.js";
|
||||
import { buildPaperclipWakePayload, PAPERCLIP_WAKE_PAYLOAD_KEY, type createHeartbeatRunPreparation } from "./run-preparation.js";
|
||||
import { buildPaperclipTaskMarkdown } from "./task-markdown.js";
|
||||
|
||||
type RunPreparation = ReturnType<typeof createHeartbeatRunPreparation>;
|
||||
type IssueContext = NonNullable<Awaited<ReturnType<RunPreparation["getIssueExecutionContext"]>>>;
|
||||
|
||||
export interface HeartbeatTaskContextInput {
|
||||
run: Pick<typeof heartbeatRuns.$inferSelect, "id">;
|
||||
agent: Pick<typeof agents.$inferSelect, "id" | "companyId" | "adapterType">;
|
||||
task: {
|
||||
issueRef: Pick<IssueContext,
|
||||
"id" | "identifier" | "title" | "status" | "priority" | "workMode" |
|
||||
"conversationAgentId" | "description" | "projectId"> | null;
|
||||
issueContext: IssueContext | null;
|
||||
wakeCommentContext: Pick<typeof issueComments.$inferSelect,
|
||||
"id" | "body" | "sourceTrust" | "presentation" | "metadata"> | null;
|
||||
context: Record<string, unknown>;
|
||||
taskSession: Pick<typeof agentTaskSessions.$inferSelect, "lastRunId"> | null;
|
||||
};
|
||||
policy: {
|
||||
trustPreset: Pick<TrustPresetResolution, "kind">;
|
||||
experimentalInstanceSettings: { enableSimplifiedEnglishInteractions?: boolean };
|
||||
};
|
||||
services: {
|
||||
issuesSvc: Pick<ReturnType<typeof issueService>, "getAncestors">;
|
||||
getPinnedSkillTestContext: RunPreparation["getPinnedSkillTestContext"];
|
||||
};
|
||||
}
|
||||
|
||||
function readNonEmptyString(value: unknown): string | null {
|
||||
return typeof value === "string" && value.trim().length > 0 ? value : null;
|
||||
}
|
||||
|
||||
/** Rebuilds task prompt fields on the run's context; acquires no execution resources. */
|
||||
export async function prepareHeartbeatTaskContext(db: Db, input: HeartbeatTaskContextInput) {
|
||||
const { run, agent } = input;
|
||||
const { issueRef, issueContext, wakeCommentContext, context, taskSession } = input.task;
|
||||
const { trustPreset, experimentalInstanceSettings } = input.policy;
|
||||
const { issuesSvc, getPinnedSkillTestContext } = input.services;
|
||||
const continuationSummary = issueRef && !isConversation(issueContext)
|
||||
? await getIssueContinuationSummaryDocument(db, issueRef.id)
|
||||
: null;
|
||||
const exposeLowTrustRaw = trustPreset.kind === "low_trust_review";
|
||||
const safeContinuationSummary =
|
||||
continuationSummary && !exposeLowTrustRaw
|
||||
? redactQuarantinedBodyForHigherTrust(continuationSummary)
|
||||
: continuationSummary;
|
||||
const safeWakeCommentContext =
|
||||
wakeCommentContext && !exposeLowTrustRaw
|
||||
? sanitizeQuarantinedCommentForHigherTrust(wakeCommentContext)
|
||||
: wakeCommentContext;
|
||||
const issueAncestors = issueRef
|
||||
? await issuesSvc.getAncestors(issueRef.id)
|
||||
: [];
|
||||
if (continuationSummary) {
|
||||
context.paperclipContinuationSummary = {
|
||||
key: safeContinuationSummary!.key,
|
||||
title: safeContinuationSummary!.title,
|
||||
body: safeContinuationSummary!.body,
|
||||
sourceTrust: safeContinuationSummary!.sourceTrust ?? null,
|
||||
updatedAt: safeContinuationSummary!.updatedAt.toISOString(),
|
||||
};
|
||||
} else {
|
||||
delete context.paperclipContinuationSummary;
|
||||
}
|
||||
const pinnedSkillTestContext =
|
||||
issueRef?.workMode === "skill_test"
|
||||
? await getPinnedSkillTestContext(agent.companyId, issueRef.id)
|
||||
: null;
|
||||
if (pinnedSkillTestContext) {
|
||||
context.paperclipSkillTest = {
|
||||
...pinnedSkillTestContext,
|
||||
directive:
|
||||
"Use this pinned file inventory as the exact skill revision under test, regardless of synced runtime skills.",
|
||||
};
|
||||
} else {
|
||||
delete context.paperclipSkillTest;
|
||||
}
|
||||
const executionContinuation =
|
||||
issueRef && !isConversation(issueContext) && issueContext?.assigneeAgentId === agent.id
|
||||
? await buildExecutionContinuation({
|
||||
db,
|
||||
companyId: agent.companyId,
|
||||
issueId: issueRef.id,
|
||||
agentId: agent.id,
|
||||
runId: run.id,
|
||||
context,
|
||||
previousContextRunId: taskSession?.lastRunId,
|
||||
summary: safeContinuationSummary?.body ?? null,
|
||||
exposeLowTrustRaw,
|
||||
})
|
||||
: null;
|
||||
context.executionContinuation = executionContinuation;
|
||||
const paperclipWakePayload = await buildPaperclipWakePayload({
|
||||
db,
|
||||
companyId: agent.companyId,
|
||||
agentId: agent.id,
|
||||
runId: run.id,
|
||||
contextSnapshot: context,
|
||||
continuationSummary,
|
||||
issueSummary: issueRef
|
||||
? {
|
||||
id: issueRef.id,
|
||||
identifier: issueRef.identifier,
|
||||
title: issueRef.title,
|
||||
description: issueContext?.description ?? null,
|
||||
status: issueRef.status,
|
||||
priority: issueRef.priority,
|
||||
workMode: issueRef.workMode,
|
||||
projectId: issueRef.projectId,
|
||||
executionPolicy: issueContext?.executionPolicy ?? null,
|
||||
}
|
||||
: null,
|
||||
exposeLowTrustRaw,
|
||||
simplifiedEnglishInteractions:
|
||||
experimentalInstanceSettings.enableSimplifiedEnglishInteractions ===
|
||||
true,
|
||||
});
|
||||
if (paperclipWakePayload) {
|
||||
context[PAPERCLIP_WAKE_PAYLOAD_KEY] = paperclipWakePayload;
|
||||
} else {
|
||||
delete context[PAPERCLIP_WAKE_PAYLOAD_KEY];
|
||||
}
|
||||
const safeWakeComments = (paperclipWakePayload?.comments ?? []).flatMap(
|
||||
(comment) =>
|
||||
typeof comment.id === "string" && typeof comment.body === "string"
|
||||
? [
|
||||
{
|
||||
id: comment.id,
|
||||
body: fastResponseHistoryBody({ body: comment.body, origin: typeof comment.origin === "string" ? comment.origin : null }),
|
||||
attachments: Array.isArray(comment.attachments)
|
||||
? comment.attachments.flatMap((attachment) => {
|
||||
const descriptor = parseObject(attachment);
|
||||
const id = readNonEmptyString(descriptor.id);
|
||||
const filename = readNonEmptyString(
|
||||
descriptor.filename,
|
||||
);
|
||||
const contentType = readNonEmptyString(
|
||||
descriptor.contentType,
|
||||
);
|
||||
const contentPath = readNonEmptyString(
|
||||
descriptor.contentPath,
|
||||
);
|
||||
const byteSize = descriptor.byteSize;
|
||||
return id &&
|
||||
filename &&
|
||||
contentType &&
|
||||
contentPath &&
|
||||
typeof byteSize === "number"
|
||||
? [
|
||||
{
|
||||
id,
|
||||
filename,
|
||||
contentType,
|
||||
byteSize,
|
||||
contentPath,
|
||||
},
|
||||
]
|
||||
: [];
|
||||
})
|
||||
: [],
|
||||
},
|
||||
]
|
||||
: [],
|
||||
);
|
||||
// Always replace caller-supplied context with the immutable, company-scoped
|
||||
// conversation snapshot. It belongs only to the endpoint's assigned agent.
|
||||
const liveVoiceGuidance = issueContext?.chatAssignedAgentId === agent.id && issueContext.chatProvider === "speko"
|
||||
? await liveVoiceExecutionGuidance(db, { companyId: agent.companyId, issueId: issueContext.id, agentId: agent.id })
|
||||
: null;
|
||||
context.paperclipTaskCommunicationGuidance =
|
||||
issueContext?.chatAssignedAgentId === agent.id
|
||||
? issueContext.chatCommunicationGuidance
|
||||
: null;
|
||||
const taskMarkdownInput = {
|
||||
conversationConfirmations: issueRef && isConversation(issueContext)
|
||||
? await getConversationConfirmationContext({ db, companyId: agent.companyId, issueId: issueRef.id, agentId: agent.id })
|
||||
: null,
|
||||
issue: issueRef
|
||||
? {
|
||||
id: issueRef.id,
|
||||
identifier: issueRef.identifier,
|
||||
title: issueRef.title,
|
||||
titleNeedsGeneration: issueContext?.titleNeedsGeneration,
|
||||
workMode: issueRef.workMode,
|
||||
conversationAgentId: issueContext?.conversationAgentId,
|
||||
description: issueRef.description,
|
||||
}
|
||||
: null,
|
||||
ancestors: issueAncestors,
|
||||
wakeComment: safeWakeCommentContext,
|
||||
wakeComments: safeWakeComments,
|
||||
attachmentOmissions: paperclipWakePayload?.attachmentOmissions,
|
||||
externalChatProvider: paperclipWakePayload?.externalChatProvider,
|
||||
slackCommand: issueContext?.chatAssignedAgentId === agent.id
|
||||
? issueContext.chatSlackCommand
|
||||
: null,
|
||||
nativeRunner: agent.adapterType === "paperclip_runner",
|
||||
interaction: {
|
||||
kind: readNonEmptyString(context.interactionKind),
|
||||
status: readNonEmptyString(context.interactionStatus),
|
||||
},
|
||||
planReview: paperclipWakePayload?.planReviewContext?.interaction
|
||||
? {
|
||||
status: paperclipWakePayload.planReviewContext.interaction.status,
|
||||
reason: paperclipWakePayload.planReviewContext.interaction.result?.reason,
|
||||
}
|
||||
: null,
|
||||
acceptedPlanContinuation:
|
||||
readNonEmptyString(context.workspaceRefreshReason) ===
|
||||
"accepted_plan_confirmation" &&
|
||||
Object.keys(parseObject(context.acceptedPlanWakeRouting)).length ===
|
||||
0,
|
||||
acceptedPlan: (() => {
|
||||
const accepted = parseObject(
|
||||
parseObject(context.planReviewInteraction).acceptedTargetRevision,
|
||||
);
|
||||
const revisionId = readNonEmptyString(accepted.revisionId);
|
||||
if (!revisionId) return null;
|
||||
return {
|
||||
documentId: readNonEmptyString(accepted.documentId),
|
||||
revisionId,
|
||||
revisionNumber:
|
||||
typeof accepted.revisionNumber === "number"
|
||||
? accepted.revisionNumber
|
||||
: null,
|
||||
};
|
||||
})(),
|
||||
};
|
||||
const taskPlan = issueRef && !isConversation(issueContext)
|
||||
? await getTaskPlanContext({
|
||||
db,
|
||||
companyId: agent.companyId,
|
||||
issueId: issueRef.id,
|
||||
approvedRevisionId: taskMarkdownInput.acceptedPlan?.revisionId,
|
||||
exposeLowTrustRaw,
|
||||
})
|
||||
: null;
|
||||
// Unlike the frozen initial communication preferences, live-call context
|
||||
// must also reach resumed turns. Rebuild it from server records each wake.
|
||||
const liveVoiceTaskPrefix = liveVoiceGuidance ? `${liveVoiceGuidance}\n\n` : "";
|
||||
let taskMarkdown = liveVoiceTaskPrefix + buildPaperclipTaskMarkdown({ ...taskMarkdownInput, taskPlan }) + chatCompletionInstruction(context);
|
||||
let taskMarkdownAssignment = liveVoiceTaskPrefix + buildPaperclipTaskMarkdown({
|
||||
...taskMarkdownInput,
|
||||
taskPlan,
|
||||
includeWakeComments: false,
|
||||
}) + chatCompletionInstruction(context);
|
||||
const taskMarkdownCompact = liveVoiceTaskPrefix + buildPaperclipTaskMarkdown({
|
||||
...taskMarkdownInput,
|
||||
taskPlan,
|
||||
includeDescription: false,
|
||||
}) + chatCompletionInstruction(context);
|
||||
const taskMarkdownAssignmentCompact = liveVoiceTaskPrefix + buildPaperclipTaskMarkdown({
|
||||
...taskMarkdownInput,
|
||||
taskPlan,
|
||||
includeDescription: false,
|
||||
includeWakeComments: false,
|
||||
}) + chatCompletionInstruction(context);
|
||||
if (issueRef) {
|
||||
context.paperclipIssue = {
|
||||
id: issueRef.id,
|
||||
identifier: issueRef.identifier,
|
||||
title: issueRef.title,
|
||||
description: isConversation(issueContext) ? null : issueRef.description,
|
||||
workMode: issueRef.workMode,
|
||||
};
|
||||
} else {
|
||||
delete context.paperclipIssue;
|
||||
}
|
||||
if (wakeCommentContext) {
|
||||
context.paperclipWakeComment = safeWakeCommentContext;
|
||||
} else {
|
||||
delete context.paperclipWakeComment;
|
||||
}
|
||||
if (taskMarkdown) {
|
||||
context.paperclipTaskMarkdown = taskMarkdown;
|
||||
} else {
|
||||
delete context.paperclipTaskMarkdown;
|
||||
}
|
||||
if (taskMarkdownAssignment) {
|
||||
context.paperclipTaskMarkdownAssignment = taskMarkdownAssignment;
|
||||
} else {
|
||||
delete context.paperclipTaskMarkdownAssignment;
|
||||
}
|
||||
if (taskMarkdownCompact && taskMarkdownCompact !== taskMarkdown) {
|
||||
context.paperclipTaskMarkdownCompact = taskMarkdownCompact;
|
||||
} else {
|
||||
delete context.paperclipTaskMarkdownCompact;
|
||||
}
|
||||
if (taskMarkdownAssignmentCompact && taskMarkdownAssignmentCompact !== taskMarkdownAssignment) {
|
||||
context.paperclipTaskMarkdownAssignmentCompact = taskMarkdownAssignmentCompact;
|
||||
} else {
|
||||
delete context.paperclipTaskMarkdownAssignmentCompact;
|
||||
}
|
||||
context.paperclipTaskCommunicationGuidance = [context.paperclipTaskCommunicationGuidance, FAST_RESPONSE_AGENT_GUIDANCE].filter(Boolean).join("\n\n");
|
||||
if (issueRef) {
|
||||
const redactedWakeContext = await createRunSecretRedactionRegistry(
|
||||
db,
|
||||
).redactForIssue(agent.companyId, issueRef.id, {
|
||||
paperclipIssue: context.paperclipIssue,
|
||||
paperclipWakeComment: context.paperclipWakeComment,
|
||||
paperclipTaskCommunicationGuidance: context.paperclipTaskCommunicationGuidance,
|
||||
paperclipTaskMarkdown: context.paperclipTaskMarkdown,
|
||||
paperclipTaskMarkdownCompact: context.paperclipTaskMarkdownCompact,
|
||||
paperclipTaskMarkdownAssignment: context.paperclipTaskMarkdownAssignment,
|
||||
paperclipTaskMarkdownAssignmentCompact: context.paperclipTaskMarkdownAssignmentCompact,
|
||||
});
|
||||
context.paperclipIssue = redactedWakeContext.paperclipIssue;
|
||||
context.paperclipTaskCommunicationGuidance = redactedWakeContext.paperclipTaskCommunicationGuidance;
|
||||
if (redactedWakeContext.paperclipWakeComment) {
|
||||
context.paperclipWakeComment =
|
||||
redactedWakeContext.paperclipWakeComment;
|
||||
}
|
||||
if (redactedWakeContext.paperclipTaskMarkdown) {
|
||||
context.paperclipTaskMarkdown =
|
||||
redactedWakeContext.paperclipTaskMarkdown;
|
||||
}
|
||||
if (redactedWakeContext.paperclipTaskMarkdownCompact) {
|
||||
context.paperclipTaskMarkdownCompact =
|
||||
redactedWakeContext.paperclipTaskMarkdownCompact;
|
||||
}
|
||||
if (redactedWakeContext.paperclipTaskMarkdownAssignment) {
|
||||
context.paperclipTaskMarkdownAssignment =
|
||||
redactedWakeContext.paperclipTaskMarkdownAssignment;
|
||||
}
|
||||
if (redactedWakeContext.paperclipTaskMarkdownAssignmentCompact) {
|
||||
context.paperclipTaskMarkdownAssignmentCompact =
|
||||
redactedWakeContext.paperclipTaskMarkdownAssignmentCompact;
|
||||
}
|
||||
}
|
||||
if (issueRef) {
|
||||
const digest = (value: string | null | undefined) =>
|
||||
value?.trim()
|
||||
? createHash("sha256")
|
||||
.update(value.trim().replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/g, ""))
|
||||
.digest("hex")
|
||||
: null;
|
||||
const redactedIssue = parseObject(context.paperclipIssue);
|
||||
context.paperclipTurnContext = {
|
||||
version: 1,
|
||||
assignment: {
|
||||
owner: "task_markdown",
|
||||
description: {
|
||||
id: issueRef.id,
|
||||
revision: digest(readNonEmptyString(redactedIssue.description)),
|
||||
},
|
||||
},
|
||||
events: {
|
||||
owner: "wake_prompt",
|
||||
comments: safeWakeComments.map((comment) => ({
|
||||
id: comment.id,
|
||||
revision: digest(comment.body),
|
||||
})),
|
||||
},
|
||||
} satisfies PaperclipTurnContext;
|
||||
} else {
|
||||
delete context.paperclipTurnContext;
|
||||
}
|
||||
return { continuationSummary, executionContinuation, paperclipWakePayload, safeWakeComments, safeWakeCommentContext };
|
||||
}
|
||||
Reference in new issue
Block a user