@geminixiang/mikan 1.0.0-beta.32 → 1.0.0-beta.34
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +42 -0
- package/dist/adapter.d.ts +11 -1
- package/dist/adapter.d.ts.map +1 -1
- package/dist/adapter.js +18 -1
- package/dist/adapter.js.map +1 -1
- package/dist/adapters/discord/bot.d.ts +1 -1
- package/dist/adapters/discord/bot.d.ts.map +1 -1
- package/dist/adapters/discord/bot.js +26 -20
- package/dist/adapters/discord/bot.js.map +1 -1
- package/dist/adapters/discord/context.d.ts +2 -1
- package/dist/adapters/discord/context.d.ts.map +1 -1
- package/dist/adapters/discord/context.js +7 -3
- package/dist/adapters/discord/context.js.map +1 -1
- package/dist/adapters/github/bot.d.ts +1 -1
- package/dist/adapters/github/bot.d.ts.map +1 -1
- package/dist/adapters/github/bot.js +10 -5
- package/dist/adapters/github/bot.js.map +1 -1
- package/dist/adapters/github/context.d.ts +2 -1
- package/dist/adapters/github/context.d.ts.map +1 -1
- package/dist/adapters/github/context.js +7 -4
- package/dist/adapters/github/context.js.map +1 -1
- package/dist/adapters/github/repo.d.ts.map +1 -1
- package/dist/adapters/github/repo.js +2 -1
- package/dist/adapters/github/repo.js.map +1 -1
- package/dist/adapters/intake.js +5 -4
- package/dist/adapters/intake.js.map +1 -1
- package/dist/adapters/shared.d.ts +8 -7
- package/dist/adapters/shared.d.ts.map +1 -1
- package/dist/adapters/shared.js +18 -16
- package/dist/adapters/shared.js.map +1 -1
- package/dist/adapters/slack/bot.d.ts +4 -1
- package/dist/adapters/slack/bot.d.ts.map +1 -1
- package/dist/adapters/slack/bot.js +76 -54
- package/dist/adapters/slack/bot.js.map +1 -1
- package/dist/adapters/slack/context.d.ts +2 -1
- package/dist/adapters/slack/context.d.ts.map +1 -1
- package/dist/adapters/slack/context.js +7 -3
- package/dist/adapters/slack/context.js.map +1 -1
- package/dist/adapters/slack/types.d.ts +2 -1
- package/dist/adapters/slack/types.d.ts.map +1 -1
- package/dist/adapters/slack/types.js.map +1 -1
- package/dist/adapters/telegram/bot.d.ts +1 -1
- package/dist/adapters/telegram/bot.d.ts.map +1 -1
- package/dist/adapters/telegram/bot.js +17 -10
- package/dist/adapters/telegram/bot.js.map +1 -1
- package/dist/adapters/telegram/context.d.ts +1 -0
- package/dist/adapters/telegram/context.d.ts.map +1 -1
- package/dist/adapters/telegram/context.js +7 -3
- package/dist/adapters/telegram/context.js.map +1 -1
- package/dist/adapters/types.d.ts +3 -2
- package/dist/adapters/types.d.ts.map +1 -1
- package/dist/adapters/types.js.map +1 -1
- package/dist/agent.d.ts +1 -0
- package/dist/agent.d.ts.map +1 -1
- package/dist/agent.js +122 -50
- package/dist/agent.js.map +1 -1
- package/dist/cli/boot.d.ts.map +1 -1
- package/dist/cli/boot.js +4 -1
- package/dist/cli/boot.js.map +1 -1
- package/dist/cli/ext-dev.d.ts.map +1 -1
- package/dist/cli/ext-dev.js +22 -14
- package/dist/cli/ext-dev.js.map +1 -1
- package/dist/cli/ext.d.ts.map +1 -1
- package/dist/cli/ext.js +5 -3
- package/dist/cli/ext.js.map +1 -1
- package/dist/cli/office.d.ts +2 -0
- package/dist/cli/office.d.ts.map +1 -0
- package/dist/cli/office.js +89 -0
- package/dist/cli/office.js.map +1 -0
- package/dist/cli/types.d.ts +3 -1
- package/dist/cli/types.d.ts.map +1 -1
- package/dist/cli/types.js.map +1 -1
- package/dist/commands/auto-reply.d.ts.map +1 -1
- package/dist/commands/auto-reply.js +2 -1
- package/dist/commands/auto-reply.js.map +1 -1
- package/dist/commands/extensions.js +1 -1
- package/dist/commands/extensions.js.map +1 -1
- package/dist/commands/login.d.ts.map +1 -1
- package/dist/commands/login.js +6 -3
- package/dist/commands/login.js.map +1 -1
- package/dist/commands/model.d.ts.map +1 -1
- package/dist/commands/model.js +7 -4
- package/dist/commands/model.js.map +1 -1
- package/dist/commands/new.d.ts.map +1 -1
- package/dist/commands/new.js +6 -2
- package/dist/commands/new.js.map +1 -1
- package/dist/commands/sandbox.d.ts.map +1 -1
- package/dist/commands/sandbox.js +5 -20
- package/dist/commands/sandbox.js.map +1 -1
- package/dist/commands/session-view.d.ts.map +1 -1
- package/dist/commands/session-view.js +2 -1
- package/dist/commands/session-view.js.map +1 -1
- package/dist/commands/types.d.ts +5 -4
- package/dist/commands/types.d.ts.map +1 -1
- package/dist/commands/types.js.map +1 -1
- package/dist/config.d.ts +15 -4
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +55 -24
- package/dist/config.js.map +1 -1
- package/dist/events.d.ts.map +1 -1
- package/dist/events.js +4 -2
- package/dist/events.js.map +1 -1
- package/dist/execution-resolver.d.ts.map +1 -1
- package/dist/execution-resolver.js +22 -13
- package/dist/execution-resolver.js.map +1 -1
- package/dist/harness/extensions/loader.d.ts +2 -1
- package/dist/harness/extensions/loader.d.ts.map +1 -1
- package/dist/harness/extensions/loader.js +5 -3
- package/dist/harness/extensions/loader.js.map +1 -1
- package/dist/harness/extensions/types.d.ts +3 -0
- package/dist/harness/extensions/types.d.ts.map +1 -1
- package/dist/harness/extensions/types.js.map +1 -1
- package/dist/harness/session-store.d.ts +2 -0
- package/dist/harness/session-store.d.ts.map +1 -1
- package/dist/harness/session-store.js +2 -0
- package/dist/harness/session-store.js.map +1 -1
- package/dist/harness/subagent-profiles.d.ts.map +1 -1
- package/dist/harness/subagent-profiles.js +9 -0
- package/dist/harness/subagent-profiles.js.map +1 -1
- package/dist/harness/subagent-runner.js +6 -4
- package/dist/harness/subagent-runner.js.map +1 -1
- package/dist/harness/types.d.ts +4 -2
- package/dist/harness/types.d.ts.map +1 -1
- package/dist/harness/types.js.map +1 -1
- package/dist/index.d.ts +2 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/main.js +47 -0
- package/dist/main.js.map +1 -1
- package/dist/observability/sentry.d.ts +2 -0
- package/dist/observability/sentry.d.ts.map +1 -1
- package/dist/observability/sentry.js +7 -0
- package/dist/observability/sentry.js.map +1 -1
- package/dist/office-address.d.ts +32 -0
- package/dist/office-address.d.ts.map +1 -0
- package/dist/office-address.js +118 -0
- package/dist/office-address.js.map +1 -0
- package/dist/office-migration.d.ts +38 -0
- package/dist/office-migration.d.ts.map +1 -0
- package/dist/office-migration.js +213 -0
- package/dist/office-migration.js.map +1 -0
- package/dist/office-registry.d.ts +81 -0
- package/dist/office-registry.d.ts.map +1 -0
- package/dist/office-registry.js +705 -0
- package/dist/office-registry.js.map +1 -0
- package/dist/packages/admin.js +5 -3
- package/dist/packages/admin.js.map +1 -1
- package/dist/packages/inspect.d.ts.map +1 -1
- package/dist/packages/inspect.js +5 -2
- package/dist/packages/inspect.js.map +1 -1
- package/dist/packages/materialize.d.ts +2 -1
- package/dist/packages/materialize.d.ts.map +1 -1
- package/dist/packages/materialize.js +6 -16
- package/dist/packages/materialize.js.map +1 -1
- package/dist/packages/resolve.d.ts.map +1 -1
- package/dist/packages/resolve.js +8 -9
- package/dist/packages/resolve.js.map +1 -1
- package/dist/packages/types.d.ts +3 -2
- package/dist/packages/types.d.ts.map +1 -1
- package/dist/packages/types.js.map +1 -1
- package/dist/provisioner.d.ts +7 -0
- package/dist/provisioner.d.ts.map +1 -1
- package/dist/provisioner.js +17 -0
- package/dist/provisioner.js.map +1 -1
- package/dist/runtime/conversation-runtime.d.ts.map +1 -1
- package/dist/runtime/conversation-runtime.js +88 -67
- package/dist/runtime/conversation-runtime.js.map +1 -1
- package/dist/runtime/session-lifecycle.d.ts +22 -12
- package/dist/runtime/session-lifecycle.d.ts.map +1 -1
- package/dist/runtime/session-lifecycle.js +85 -53
- package/dist/runtime/session-lifecycle.js.map +1 -1
- package/dist/runtime/types.d.ts +14 -4
- package/dist/runtime/types.d.ts.map +1 -1
- package/dist/runtime/types.js.map +1 -1
- package/dist/sandbox/cloudflare.d.ts.map +1 -1
- package/dist/sandbox/cloudflare.js +1 -0
- package/dist/sandbox/cloudflare.js.map +1 -1
- package/dist/sandbox/container.d.ts.map +1 -1
- package/dist/sandbox/container.js +1 -0
- package/dist/sandbox/container.js.map +1 -1
- package/dist/sandbox/firecracker.d.ts.map +1 -1
- package/dist/sandbox/firecracker.js +1 -0
- package/dist/sandbox/firecracker.js.map +1 -1
- package/dist/sandbox/gondolin.d.ts.map +1 -1
- package/dist/sandbox/gondolin.js +1 -0
- package/dist/sandbox/gondolin.js.map +1 -1
- package/dist/sandbox/host.d.ts.map +1 -1
- package/dist/sandbox/host.js +1 -0
- package/dist/sandbox/host.js.map +1 -1
- package/dist/sandbox/identity.d.ts +35 -7
- package/dist/sandbox/identity.d.ts.map +1 -1
- package/dist/sandbox/identity.js +31 -5
- package/dist/sandbox/identity.js.map +1 -1
- package/dist/sandbox/image.d.ts.map +1 -1
- package/dist/sandbox/image.js +1 -0
- package/dist/sandbox/image.js.map +1 -1
- package/dist/sandbox/index.d.ts +2 -0
- package/dist/sandbox/index.d.ts.map +1 -1
- package/dist/sandbox/index.js +12 -0
- package/dist/sandbox/index.js.map +1 -1
- package/dist/sandbox/types.d.ts +6 -0
- package/dist/sandbox/types.d.ts.map +1 -1
- package/dist/sandbox/types.js.map +1 -1
- package/dist/sessions/chat-history-sync.d.ts.map +1 -1
- package/dist/sessions/chat-history-sync.js +33 -4
- package/dist/sessions/chat-history-sync.js.map +1 -1
- package/dist/sessions/store.d.ts +13 -1
- package/dist/sessions/store.d.ts.map +1 -1
- package/dist/sessions/store.js +78 -9
- package/dist/sessions/store.js.map +1 -1
- package/dist/settings-mutation.d.ts +3 -3
- package/dist/settings-mutation.d.ts.map +1 -1
- package/dist/settings-mutation.js +4 -4
- package/dist/settings-mutation.js.map +1 -1
- package/dist/store.d.ts +5 -0
- package/dist/store.d.ts.map +1 -1
- package/dist/store.js +13 -5
- package/dist/store.js.map +1 -1
- package/dist/tools/event.d.ts.map +1 -1
- package/dist/tools/event.js +5 -2
- package/dist/tools/event.js.map +1 -1
- package/dist/tools/subagent.d.ts.map +1 -1
- package/dist/tools/subagent.js +6 -3
- package/dist/tools/subagent.js.map +1 -1
- package/dist/trigger.d.ts.map +1 -1
- package/dist/trigger.js +6 -3
- package/dist/trigger.js.map +1 -1
- package/dist/types.d.ts +78 -9
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/dist/vault/index.d.ts +16 -0
- package/dist/vault/index.d.ts.map +1 -1
- package/dist/vault/index.js +31 -1
- package/dist/vault/index.js.map +1 -1
- package/dist/web/admin/portal.d.ts +13 -0
- package/dist/web/admin/portal.d.ts.map +1 -1
- package/dist/web/admin/portal.js +156 -173
- package/dist/web/admin/portal.js.map +1 -1
- package/dist/web/admin/types.d.ts +3 -3
- package/dist/web/admin/types.d.ts.map +1 -1
- package/dist/web/admin/types.js.map +1 -1
- package/dist/web/session-view/portal.d.ts.map +1 -1
- package/dist/web/session-view/portal.js +24 -14
- package/dist/web/session-view/portal.js.map +1 -1
- package/dist/web/session-view/service.d.ts +1 -1
- package/dist/web/session-view/service.d.ts.map +1 -1
- package/dist/web/session-view/service.js +48 -11
- package/dist/web/session-view/service.js.map +1 -1
- package/dist/workspace-projection/index.d.ts +10 -3
- package/dist/workspace-projection/index.d.ts.map +1 -1
- package/dist/workspace-projection/index.js +129 -45
- package/dist/workspace-projection/index.js.map +1 -1
- package/dist/workspace-projection/types.d.ts +14 -3
- package/dist/workspace-projection/types.d.ts.map +1 -1
- package/dist/workspace-projection/types.js.map +1 -1
- package/package.json +2 -1
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { existsSync } from "fs";
|
|
2
2
|
import { dirname, join } from "path";
|
|
3
3
|
import { Type } from "@sinclair/typebox";
|
|
4
|
+
import { createConversationEvent, } from "../../adapter.js";
|
|
4
5
|
import * as log from "../../log.js";
|
|
5
6
|
import { ensureDirExists, readJsonSchemaFileIfExists } from "../../utils/file-guards.js";
|
|
6
7
|
import { atomicWritePrivateFile } from "../../utils/fs-atomic.js";
|
|
@@ -11,6 +12,8 @@ import { GithubClient, GITHUB_MAX_COMMENT_LENGTH, githubRetry } from "./client.j
|
|
|
11
12
|
import { createGithubAdapters } from "./context.js";
|
|
12
13
|
import { fetchIsPr, fetchPrHeadBranch, GithubOps } from "./github-ops.js";
|
|
13
14
|
import { cloneRepo, conversationRepoDir } from "./repo.js";
|
|
15
|
+
import { conversationOfficeDir, createOfficeAddress } from "../../office-address.js";
|
|
16
|
+
import { ensureOfficeDir } from "../../office-registry.js";
|
|
14
17
|
import { buildGithubConversationId, GITHUB_ISSUE_BODY_TS, githubReviewCommentTs, parseGithubConversationId, parseReviewCommentTs, } from "./ids.js";
|
|
15
18
|
const SyncStateSchema = Type.Object({
|
|
16
19
|
repos: Type.Record(Type.String(), Type.Object({
|
|
@@ -250,10 +253,10 @@ export class GithubMessagingBot {
|
|
|
250
253
|
await githubRetry(() => this.client.deleteIssueComment(ref.owner, ref.repo, commentId));
|
|
251
254
|
}
|
|
252
255
|
logToFile(conversationId, entry) {
|
|
253
|
-
appendChannelLog(this.config.workingDir, conversationId, entry);
|
|
256
|
+
appendChannelLog(this.config.workingDir, createOfficeAddress("github", conversationId), entry);
|
|
254
257
|
}
|
|
255
258
|
logBotResponse(conversationId, text, ts) {
|
|
256
|
-
appendBotResponseLog(this.config.workingDir, conversationId, text, ts);
|
|
259
|
+
appendBotResponseLog(this.config.workingDir, createOfficeAddress("github", conversationId), text, ts);
|
|
257
260
|
}
|
|
258
261
|
// ==========================================================================
|
|
259
262
|
// Private - polling
|
|
@@ -415,7 +418,7 @@ export class GithubMessagingBot {
|
|
|
415
418
|
return (pattern ? text.replace(pattern, "") : text).trim();
|
|
416
419
|
}
|
|
417
420
|
isParticipating(conversationId) {
|
|
418
|
-
return existsSync(join(this.config.workingDir, conversationId, "log.jsonl"));
|
|
421
|
+
return existsSync(join(conversationOfficeDir(this.config.workingDir, createOfficeAddress("github", conversationId)), "log.jsonl"));
|
|
419
422
|
}
|
|
420
423
|
/**
|
|
421
424
|
* True when `user` holds at least write permission on the repo. Fails
|
|
@@ -470,7 +473,8 @@ export class GithubMessagingBot {
|
|
|
470
473
|
const messageText = item.review
|
|
471
474
|
? await this.formatReviewMessage(item, cleanedText)
|
|
472
475
|
: cleanedText;
|
|
473
|
-
const eventBase = {
|
|
476
|
+
const eventBase = createConversationEvent({
|
|
477
|
+
platform: "github",
|
|
474
478
|
type: item.ts === GITHUB_ISSUE_BODY_TS ? "issue" : "message",
|
|
475
479
|
conversationId,
|
|
476
480
|
conversationKind: "shared",
|
|
@@ -479,7 +483,7 @@ export class GithubMessagingBot {
|
|
|
479
483
|
user: item.user,
|
|
480
484
|
userName: item.user,
|
|
481
485
|
text: messageText,
|
|
482
|
-
};
|
|
486
|
+
});
|
|
483
487
|
await processMessageIntake({
|
|
484
488
|
eventBase,
|
|
485
489
|
workingDir: this.config.workingDir,
|
|
@@ -617,6 +621,7 @@ export class GithubMessagingBot {
|
|
|
617
621
|
if (existsSync(dir))
|
|
618
622
|
return;
|
|
619
623
|
try {
|
|
624
|
+
ensureOfficeDir(this.config.workingDir, createOfficeAddress("github", conversationId));
|
|
620
625
|
const token = await this.client.createScopedInstallationToken(ref.repo, {
|
|
621
626
|
contents: "read",
|
|
622
627
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bot.js","sourceRoot":"","sources":["../../../src/adapters/github/bot.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,IAAI,CAAC;AAChC,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AACrC,OAAO,EAAE,IAAI,EAAE,MAAM,mBAAmB,CAAC;AAOzC,OAAO,KAAK,GAAG,MAAM,cAAc,CAAC;AACpC,OAAO,EAAE,eAAe,EAAE,0BAA0B,EAAE,MAAM,4BAA4B,CAAC;AACzF,OAAO,EAAE,sBAAsB,EAAE,MAAM,0BAA0B,CAAC;AAClE,OAAO,EAAE,qBAAqB,EAAE,MAAM,0BAA0B,CAAC;AACjE,OAAO,EACL,oBAAoB,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M,iBAAiB,CAAC,IAAI,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;YAClF,MAAM,SAAS,CAAC;gBACd,GAAG,EAAE,sBAAsB,GAAG,CAAC,KAAK,IAAI,GAAG,CAAC,IAAI,MAAM;gBACtD,GAAG;gBACH,KAAK;gBACL,QAAQ,EAAE,GAAG,IAAI,CAAC,OAAO,OAAO;gBAChC,QAAQ,EAAE,IAAI,CAAC,QAAQ,IAAI,GAAG,IAAI,CAAC,OAAO,gCAAgC;gBAC1E,QAAQ,EAAE,IAAI,CAAC,CAAC,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,SAAS;gBACvC,YAAY;aACb,CAAC,CAAC;YACH,GAAG,CAAC,OAAO,CACT,IAAI,cAAc,YAAY,GAAG,CAAC,KAAK,IAAI,GAAG,CAAC,IAAI,GAAG,IAAI,CAAC,CAAC,CAAC,wBAAwB,GAAG,CAAC,MAAM,YAAY,YAAY,IAAI,MAAM,GAAG,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,CAAC,EAAE,EAAE,CACvJ,CAAC;QACJ,CAAC;QAAC,OAAO,GAAG,EAAE,CAAC;YACb,GAAG,CAAC,UAAU,CACZ,iCAAiC,cAAc,EAAE,EACjD,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CACjD,CAAC;QACJ,CAAC;IACH,CAAC;CACF","sourcesContent":["import { existsSync } from \"fs\";\nimport { dirname, join } from \"path\";\nimport { Type } from \"@sinclair/typebox\";\nimport type {\n ConversationEvent,\n MessagingBot,\n MessagingEventHandler,\n MessagingInfo,\n} from \"../../adapter.js\";\nimport * as log from \"../../log.js\";\nimport { ensureDirExists, readJsonSchemaFileIfExists } from \"../../utils/file-guards.js\";\nimport { atomicWritePrivateFile } from \"../../utils/fs-atomic.js\";\nimport { resolveChatSessionKey } from \"../../sessions/policy.js\";\nimport {\n appendBotResponseLog,\n appendChannelLog,\n MessagingEventQueue,\n splitText,\n} from \"../shared.js\";\nimport { processMessageIntake } from \"../intake.js\";\nimport { GithubClient, GITHUB_MAX_COMMENT_LENGTH, githubRetry } from \"./client.js\";\nimport { createGithubAdapters } from \"./context.js\";\nimport { fetchIsPr, fetchPrHeadBranch, GithubOps } from \"./github-ops.js\";\nimport { cloneRepo, conversationRepoDir } from \"./repo.js\";\nimport {\n buildGithubConversationId,\n GITHUB_ISSUE_BODY_TS,\n githubReviewCommentTs,\n parseGithubConversationId,\n parseReviewCommentTs,\n} from \"./ids.js\";\nimport type {\n GithubBotConfig,\n GithubConversationRef,\n GithubEvent,\n GithubIssue,\n GithubReactionContent,\n GithubRepoRef,\n GithubSyncState,\n} from \"./types.js\";\n\nconst SyncStateSchema = Type.Object({\n repos: Type.Record(\n Type.String(),\n Type.Object({\n baseline: Type.String(),\n cursor: Type.String(),\n seenComments: Type.Array(Type.Number()),\n seenIssues: Type.Array(Type.Number()),\n // Optional: state files written before review-comment polling must keep\n // loading — a schema failure re-baselines and silently drops dedup state.\n seenReviewComments: Type.Optional(Type.Array(Type.Number())),\n }),\n ),\n});\n\n/**\n * Re-fetch this far behind the cursor each poll. Dedup is by id (the\n * watermark), so the overlap only costs bandwidth and closes the boundary\n * races of a bare `since` timestamp (DESIGN.md § Event source).\n */\nconst POLL_OVERLAP_MS = 5 * 60 * 1000;\n\nconst MAX_SEEN_IDS = 5000;\n\n/** Effective role → rank, for the trigger-permission gate. */\nconst PERMISSION_RANK: Record<string, number> = {\n none: 0,\n read: 1,\n triage: 2,\n write: 3,\n maintain: 4,\n admin: 5,\n};\n\n/**\n * Commenters need write or better to trigger the agent. Fixed, not a config\n * knob: it guards public repos (anyone can comment there), and the people who\n * ask an agent to change code are exactly the people with push access.\n */\nconst REQUIRED_TRIGGER_RANK = PERMISSION_RANK.write;\n\n/** Permission lookups are cached this long per repo+user. */\nconst PERMISSION_CACHE_TTL_MS = 5 * 60 * 1000;\n\n/** In-memory form of one repo's persisted watermark. */\ninterface RepoWatermark {\n baseline: string;\n cursor: string;\n seenComments: Set<number>;\n seenIssues: Set<number>;\n seenReviewComments: Set<number>;\n}\n\nexport const formatGithubContinuation = (partNum: number): string => `*(continued ${partNum})*`;\n\n/** Slack-style emoji short names → GitHub reaction content values. */\nconst GITHUB_REACTIONS: Record<string, GithubReactionContent> = {\n \"+1\": \"+1\",\n thumbsup: \"+1\",\n \"-1\": \"-1\",\n thumbsdown: \"-1\",\n laugh: \"laugh\",\n smile: \"laugh\",\n confused: \"confused\",\n heart: \"heart\",\n hooray: \"hooray\",\n tada: \"hooray\",\n rocket: \"rocket\",\n eyes: \"eyes\",\n};\n\ninterface IncomingItem {\n ref: GithubConversationRef;\n /** Comment id, rc-<id> for review comments, or GITHUB_ISSUE_BODY_TS for the body. */\n ts: string;\n user: string;\n text: string;\n createdAt: string;\n /** Known only for issue-body items; comment first-contact resolves it via getIssue. */\n isPr?: boolean;\n /** Present for inline PR review comments: the diff anchor to inject as context. */\n review?: {\n commentId: number;\n path: string;\n line: number | null;\n diffHunk: string;\n inReplyToId?: number;\n };\n}\n\n// Repo refs are lowercased at every entry point (env config here, the\n// installation API in start()) so conversation ids and sync-state keys never\n// depend on how a repo's name was spelled — GitHub is case-insensitive.\nfunction parseRepoList(repos: string[]): GithubRepoRef[] {\n return repos.map((entry) => {\n const [owner, repo, ...rest] = entry.split(\"/\");\n if (!owner || !repo || rest.length > 0) {\n throw new Error(`Invalid GITHUB_REPOS entry (expected owner/repo): ${entry}`);\n }\n return { owner: owner.toLowerCase(), repo: repo.toLowerCase() };\n });\n}\n\n/** Sets iterate in insertion order; drop the oldest ids once over the cap. */\nfunction pruneSeen(seen: Set<number>): void {\n if (seen.size <= MAX_SEEN_IDS) return;\n let toDrop = seen.size - MAX_SEEN_IDS / 2;\n for (const id of seen) {\n if (toDrop-- <= 0) break;\n seen.delete(id);\n }\n}\n\n/** Issue number from a comment's `issue_url` (…/repos/o/r/issues/42). */\nfunction issueNumberFromUrl(issueUrl: string): number {\n const match = /\\/issues\\/(\\d+)$/.exec(issueUrl);\n if (!match) {\n throw new Error(`Cannot parse issue number from ${issueUrl}`);\n }\n return Number(match[1]);\n}\n\n/** PR number from a review comment's `pull_request_url` (…/repos/o/r/pulls/42). */\nfunction prNumberFromUrl(pullRequestUrl: string): number {\n const match = /\\/pulls\\/(\\d+)$/.exec(pullRequestUrl);\n if (!match) {\n throw new Error(`Cannot parse PR number from ${pullRequestUrl}`);\n }\n return Number(match[1]);\n}\n\n/** Keep the tail: a review comment anchors to the hunk's final lines. */\nconst MAX_DIFF_HUNK_CHARS = 1500;\nconst MAX_THREAD_TURNS = 10;\nconst MAX_THREAD_TURN_CHARS = 500;\n\nexport class GithubMessagingBot implements MessagingBot {\n private readonly client: GithubClient;\n private readonly handler: MessagingEventHandler;\n private readonly config: GithubBotConfig;\n /** Host-side backend for the github_* tool pack; standalone from polling. */\n readonly ops: GithubOps;\n private appSlug: string | null = null;\n private botEmail: string | null = null;\n private watchedRepos: GithubRepoRef[] = [];\n private queues = new Map<string, MessagingEventQueue>();\n private repoState = new Map<string, RepoWatermark>();\n private permissionCache = new Map<string, { rank: number; expiresAt: number }>();\n private pollInFlight = false;\n\n constructor(handler: MessagingEventHandler, config: GithubBotConfig, client?: GithubClient) {\n this.handler = handler;\n this.config = config;\n this.client =\n client ??\n new GithubClient({\n appId: config.appId,\n privateKey: config.privateKey,\n installationId: config.installationId,\n });\n this.ops = new GithubOps(this.client, {\n workingDir: config.workingDir,\n cloudBuild: config.cloudBuild,\n });\n }\n\n // ==========================================================================\n // Public API (implements MessagingBot)\n // ==========================================================================\n\n async start(): Promise<void> {\n this.appSlug = await this.client.getAppSlug();\n // Canonical noreply author email (<user-id>+<login>@users.noreply.github.com)\n // so the bot's commits link to its avatar/profile; degrade to a plain\n // noreply spelling when the lookup fails.\n try {\n const botUserId = await this.client.getUserId(`${this.appSlug}[bot]`);\n this.botEmail = `${botUserId}+${this.appSlug}[bot]@users.noreply.github.com`;\n } catch {\n this.botEmail = `${this.appSlug}[bot]@users.noreply.github.com`;\n }\n this.watchedRepos =\n this.config.repos.length > 0\n ? parseRepoList(this.config.repos)\n : (await this.client.listInstallationRepositories()).map((repository) => ({\n owner: repository.owner.login.toLowerCase(),\n repo: repository.name.toLowerCase(),\n }));\n if (this.watchedRepos.length === 0) {\n log.logWarning(\"GitHub: installation has no repositories; nothing to poll\");\n }\n\n // Restore persisted watermarks; a repo watched for the first time gets a\n // baseline of \"now\" so history never triggers (DESIGN.md § Event source).\n const persisted = this.loadSyncState();\n const now = new Date().toISOString();\n for (const repo of this.watchedRepos) {\n const repoKey = `${repo.owner}/${repo.repo}`;\n const saved = persisted?.repos[repoKey];\n this.repoState.set(\n repoKey,\n saved\n ? {\n baseline: saved.baseline,\n cursor: saved.cursor,\n seenComments: new Set(saved.seenComments),\n seenIssues: new Set(saved.seenIssues),\n seenReviewComments: new Set(saved.seenReviewComments ?? []),\n }\n : {\n baseline: now,\n cursor: now,\n seenComments: new Set(),\n seenIssues: new Set(),\n seenReviewComments: new Set(),\n },\n );\n }\n this.persistSyncState();\n\n setInterval(() => {\n void this.poll();\n }, this.config.pollIntervalMs).unref();\n\n log.logConnected(\"GitHub\");\n log.logInfo(\n `GitHub bot started as @${this.appSlug}[bot], polling ${this.watchedRepos.length} repo(s) every ${Math.round(this.config.pollIntervalMs / 1000)}s`,\n );\n }\n\n async postMessage(channel: string, text: string): Promise<string> {\n const ref = parseGithubConversationId(channel);\n const parts = splitText(text, GITHUB_MAX_COMMENT_LENGTH, formatGithubContinuation);\n const firstId = await this.postComment(ref, parts[0]);\n for (const part of parts.slice(1)) {\n await this.postComment(ref, part);\n }\n return String(firstId);\n }\n\n async updateMessage(channel: string, ts: string, text: string): Promise<void> {\n const ref = parseGithubConversationId(channel);\n await githubRetry(() => this.client.updateIssueComment(ref.owner, ref.repo, Number(ts), text));\n }\n\n async addReaction(channel: string, messageTs: string, emoji: string): Promise<void> {\n const ref = parseGithubConversationId(channel);\n const content = GITHUB_REACTIONS[emoji.replace(/^:|:$/g, \"\")];\n if (!content) {\n throw new Error(\n `GitHub does not support reaction '${emoji}' (supported: ${Object.keys(GITHUB_REACTIONS).join(\", \")})`,\n );\n }\n const reviewCommentId = parseReviewCommentTs(messageTs);\n await githubRetry(() => {\n if (messageTs === GITHUB_ISSUE_BODY_TS) {\n return this.client.createIssueReaction(ref.owner, ref.repo, ref.number, content);\n }\n if (reviewCommentId !== null) {\n return this.client.createReviewCommentReaction(\n ref.owner,\n ref.repo,\n reviewCommentId,\n content,\n );\n }\n return this.client.createCommentReaction(ref.owner, ref.repo, Number(messageTs), content);\n });\n }\n\n enqueueEvent(event: ConversationEvent): boolean {\n const conversationId = event.conversationId;\n const queue = this.getQueue(conversationId);\n if (queue.size() >= 5) {\n log.logWarning(\n `Event queue full for ${conversationId}, discarding: ${event.text.substring(0, 50)}`,\n );\n return false;\n }\n log.logInfo(`Enqueueing event for ${conversationId}: ${event.text.substring(0, 50)}`);\n queue.enqueue(() => {\n const context = createGithubAdapters(event as GithubEvent, this);\n return this.handler.handleEvent(event, this, context);\n });\n return true;\n }\n\n getMessagingInfo(): MessagingInfo {\n return {\n name: \"github\",\n trustModel: \"open-trigger\",\n formattingGuide:\n \"## GitHub Formatting (GitHub Flavored Markdown)\\n\" +\n \"Standard Markdown plus tables, task lists, fenced code blocks, and ```suggestion blocks.\\n\" +\n \"Reference issues/PRs as #123 and users as @login (mentions notify people — use sparingly).\",\n channels: [],\n users: [],\n };\n }\n\n // ==========================================================================\n // Internal helpers (used by context.ts)\n // ==========================================================================\n\n async postComment(ref: GithubConversationRef, text: string): Promise<number> {\n const comment = await githubRetry(() =>\n this.client.createIssueComment(ref.owner, ref.repo, ref.number, text),\n );\n return comment.id;\n }\n\n async deleteComment(ref: GithubConversationRef, commentId: number): Promise<void> {\n await githubRetry(() => this.client.deleteIssueComment(ref.owner, ref.repo, commentId));\n }\n\n logToFile(conversationId: string, entry: object): void {\n appendChannelLog(this.config.workingDir, conversationId, entry);\n }\n\n logBotResponse(conversationId: string, text: string, ts: string): void {\n appendBotResponseLog(this.config.workingDir, conversationId, text, ts);\n }\n\n // ==========================================================================\n // Private - polling\n // ==========================================================================\n\n private getQueue(conversationId: string): MessagingEventQueue {\n let queue = this.queues.get(conversationId);\n if (!queue) {\n queue = new MessagingEventQueue(\"GitHub\");\n this.queues.set(conversationId, queue);\n }\n return queue;\n }\n\n /** One poll tick over every watched repo. Public for tests. */\n async poll(): Promise<void> {\n if (this.pollInFlight) return;\n this.pollInFlight = true;\n try {\n let changed = false;\n for (const repo of this.watchedRepos) {\n try {\n changed = (await this.pollRepo(repo)) || changed;\n } catch (err) {\n log.logWarning(\n `GitHub poll failed for ${repo.owner}/${repo.repo}`,\n err instanceof Error ? err.message : String(err),\n );\n }\n }\n if (changed) {\n this.persistSyncState();\n }\n } finally {\n this.pollInFlight = false;\n }\n }\n\n private async pollRepo(repo: GithubRepoRef): Promise<boolean> {\n const repoKey = `${repo.owner}/${repo.repo}`;\n const state = this.repoState.get(repoKey);\n if (!state) return false;\n const since = new Date(Date.parse(state.cursor) - POLL_OVERLAP_MS).toISOString();\n let changed = false;\n\n // Comment activity also bumps the parent issue's updated_at, so the issues\n // list mostly echoes the comments list; only issues *created* since the\n // baseline are new conversations (their body is the first message).\n const issues = (await this.client.listIssuesSince(repo.owner, repo.repo, since)) ?? [];\n changed =\n (await this.advanceFeed(state, state.seenIssues, issues, (issue) => ({\n ref: { ...repo, number: issue.number },\n ts: GITHUB_ISSUE_BODY_TS,\n user: issue.user.login,\n text: `# ${issue.title}\\n\\n${issue.body ?? \"\"}`.trim(),\n createdAt: issue.created_at,\n isPr: Boolean(issue.pull_request),\n }))) || changed;\n\n const comments = (await this.client.listIssueCommentsSince(repo.owner, repo.repo, since)) ?? [];\n changed =\n (await this.advanceFeed(state, state.seenComments, comments, (comment) => ({\n ref: { ...repo, number: issueNumberFromUrl(comment.issue_url) },\n ts: String(comment.id),\n user: comment.user.login,\n text: comment.body,\n createdAt: comment.created_at,\n }))) || changed;\n\n // Inline PR review comments live in their own endpoint and id space; the\n // same watermark discipline applies. The bot's own thread replies (the\n // github_review_reply tool) re-surface here and are dropped as Bot-authored.\n const reviewComments =\n (await this.client.listPullReviewCommentsSince(repo.owner, repo.repo, since)) ?? [];\n changed =\n (await this.advanceFeed(state, state.seenReviewComments, reviewComments, (comment) => ({\n ref: { ...repo, number: prNumberFromUrl(comment.pull_request_url) },\n ts: githubReviewCommentTs(comment.id),\n user: comment.user.login,\n text: comment.body,\n createdAt: comment.created_at,\n isPr: true,\n review: {\n commentId: comment.id,\n path: comment.path,\n line: comment.line,\n diffHunk: comment.diff_hunk,\n inReplyToId: comment.in_reply_to_id,\n },\n }))) || changed;\n\n pruneSeen(state.seenComments);\n pruneSeen(state.seenIssues);\n pruneSeen(state.seenReviewComments);\n return changed;\n }\n\n /**\n * One feed's watermark advance — the same discipline for all three feeds:\n * bump the cursor on any fresher updated_at, then let the id watermark plus\n * the creation baseline decide what actually triggers (edits re-surface old\n * items with a fresh updated_at). Bot-authored items advance the watermark\n * without triggering.\n */\n private async advanceFeed<\n T extends {\n id: number;\n created_at: string;\n updated_at: string;\n user: { login: string; type: string };\n },\n >(\n state: RepoWatermark,\n seen: Set<number>,\n items: T[],\n toIncoming: (item: T) => IncomingItem,\n ): Promise<boolean> {\n let changed = false;\n for (const item of items) {\n if (item.updated_at > state.cursor) {\n state.cursor = item.updated_at;\n changed = true;\n }\n if (item.created_at < state.baseline || seen.has(item.id)) continue;\n seen.add(item.id);\n changed = true;\n if (item.user.type === \"Bot\") continue;\n await this.handleIncoming(toIncoming(item));\n }\n return changed;\n }\n\n // ==========================================================================\n // Private - watermark persistence\n // ==========================================================================\n\n private loadSyncState(): GithubSyncState | undefined {\n try {\n return readJsonSchemaFileIfExists(\n this.config.syncStatePath,\n SyncStateSchema,\n (detail) => `Malformed GitHub sync state at ${this.config.syncStatePath}: ${detail}`,\n );\n } catch (err) {\n // A bad state file re-baselines (history won't trigger) rather than\n // blocking startup; the next persist overwrites it.\n log.logWarning(\n \"GitHub: ignoring unreadable sync state\",\n err instanceof Error ? err.message : String(err),\n );\n return undefined;\n }\n }\n\n /** The persisted form of the current watermarks; the test/inspection surface. */\n syncStateSnapshot(): GithubSyncState {\n const state: GithubSyncState = { repos: {} };\n for (const [repoKey, watermark] of this.repoState) {\n state.repos[repoKey] = {\n baseline: watermark.baseline,\n cursor: watermark.cursor,\n seenComments: [...watermark.seenComments],\n seenIssues: [...watermark.seenIssues],\n seenReviewComments: [...watermark.seenReviewComments],\n };\n }\n return state;\n }\n\n private persistSyncState(): void {\n ensureDirExists(dirname(this.config.syncStatePath));\n atomicWritePrivateFile(this.config.syncStatePath, JSON.stringify(this.syncStateSnapshot()));\n }\n\n // ==========================================================================\n // Private - triggering\n // ==========================================================================\n\n /** Fresh regex per call: the `g` flag makes `test`/`replace` stateful. */\n private mentionPattern(): RegExp | null {\n return this.appSlug ? new RegExp(`@${this.appSlug}(?![\\\\w-])`, \"gi\") : null;\n }\n\n private isMentioned(text: string): boolean {\n const pattern = this.mentionPattern();\n return pattern ? pattern.test(text) : false;\n }\n\n private stripMention(text: string): string {\n const pattern = this.mentionPattern();\n return (pattern ? text.replace(pattern, \"\") : text).trim();\n }\n\n private isParticipating(conversationId: string): boolean {\n return existsSync(join(this.config.workingDir, conversationId, \"log.jsonl\"));\n }\n\n /**\n * True when `user` holds at least write permission on the repo. Fails\n * closed: a failed lookup denies the trigger (and logs) rather than\n * letting an unverified commenter drive the agent.\n */\n private async hasTriggerPermission(ref: GithubConversationRef, user: string): Promise<boolean> {\n const cacheKey = `${ref.owner}/${ref.repo}#${user}`;\n const cached = this.permissionCache.get(cacheKey);\n if (cached && Date.now() < cached.expiresAt) {\n return cached.rank >= REQUIRED_TRIGGER_RANK;\n }\n let rank: number;\n try {\n const role = await githubRetry(() =>\n this.client.getCollaboratorPermission(ref.owner, ref.repo, user),\n );\n // Custom role_name values are unrankable; the legacy permission field\n // still carries their closest standard mapping, so take the stronger.\n rank = Math.max(\n PERMISSION_RANK[role.role_name ?? \"\"] ?? 0,\n PERMISSION_RANK[role.permission] ?? 0,\n );\n } catch (err) {\n log.logWarning(\n `GitHub: permission lookup failed for ${user} on ${ref.owner}/${ref.repo}; denying trigger`,\n err instanceof Error ? err.message : String(err),\n );\n return false;\n }\n this.permissionCache.set(cacheKey, {\n rank,\n expiresAt: Date.now() + PERMISSION_CACHE_TTL_MS,\n });\n return rank >= REQUIRED_TRIGGER_RANK;\n }\n\n private async handleIncoming(item: IncomingItem): Promise<void> {\n const conversationId = buildGithubConversationId(item.ref);\n const mentioned = this.isMentioned(item.text);\n const participating = this.isParticipating(conversationId);\n // Narrow trigger (DESIGN.md): only threads the bot is mentioned in or\n // already participates in. Everything else is ignored without logging so\n // busy repos don't grow conversation dirs for untouched issues.\n if (!mentioned && !participating) return;\n\n // Permission gate: on public repos anyone can comment, so a mention from\n // anyone below write permission is ignored entirely (no log, no state).\n if (!(await this.hasTriggerPermission(item.ref, item.user))) {\n log.logInfo(\n `GitHub: ignoring ${conversationId} comment from ${item.user} (below write permission)`,\n );\n return;\n }\n\n const cleanedText = this.stripMention(item.text);\n const sessionKey = resolveChatSessionKey({\n conversationId,\n conversationKind: \"shared\",\n messageId: item.ts,\n persistentTopLevel: true,\n });\n\n const messageText = item.review\n ? await this.formatReviewMessage(item, cleanedText)\n : cleanedText;\n\n const eventBase: GithubEvent = {\n type: item.ts === GITHUB_ISSUE_BODY_TS ? \"issue\" : \"message\",\n conversationId,\n conversationKind: \"shared\",\n ts: item.ts,\n sessionKey,\n user: item.user,\n userName: item.user,\n text: messageText,\n };\n\n await processMessageIntake({\n eventBase,\n workingDir: this.config.workingDir,\n isAutoReplyCandidate: false,\n // Match on the user-typed text, not the review-decorated messageText.\n magicWord: { text: cleanedText, addressed: mentioned, scopeFallback: \"never\" },\n busyPolicy: \"queue\",\n logEntryBase: {\n date: item.createdAt,\n ts: item.ts,\n user: item.user,\n userName: item.user,\n text: messageText,\n isMessagingBot: false,\n },\n log: (entry) => this.logToFile(conversationId, entry),\n // GitHub has no attachments; the prep hook is used to lay down the\n // issue context and repo clone only for messages that will dispatch,\n // and before the comment itself is logged.\n processAttachments: async () => {\n await this.prepareConversation(item, conversationId, participating);\n return [];\n },\n queueKey: conversationId,\n enqueue: (queueKey, work) => this.getQueue(queueKey).enqueue(work),\n handler: this.handler,\n bot: this,\n createContext: (event) => createGithubAdapters(event, this),\n });\n }\n\n /**\n * First contact: log the issue title/body ahead of the comment so the\n * session history starts with what the thread is about. The clone is\n * (re)attempted on every trigger while ./repo is missing — a no-op once\n * it exists — so a failed first clone (e.g. App permissions granted\n * later) heals on the next mention instead of wedging the conversation.\n */\n private async prepareConversation(\n item: IncomingItem,\n conversationId: string,\n participating: boolean,\n ): Promise<void> {\n let isPrHint = item.isPr;\n if (!participating && item.ts !== GITHUB_ISSUE_BODY_TS) {\n const issue = await this.logIssueContext(item.ref, conversationId, item.createdAt);\n // Only comments arrive without the PR-ness hint; review comments carry\n // isPr: true (they only exist on PRs) and that knowledge is authoritative.\n if (issue && isPrHint === undefined) isPrHint = Boolean(issue.pull_request);\n }\n if (!existsSync(conversationRepoDir(this.config.workingDir, conversationId))) {\n const isPr = isPrHint ?? (await fetchIsPr(this.client, item.ref));\n await this.ensureRepoClone(item.ref, conversationId, isPr);\n }\n }\n\n /**\n * Decorates an inline review comment with its diff anchor and (for replies)\n * the thread's earlier turns, so the agent knows which code the feedback is\n * about without hunting through the PR. The rc-<id> in the header is what\n * github_review_reply takes to answer in-thread.\n */\n private async formatReviewMessage(item: IncomingItem, cleanedText: string): Promise<string> {\n const review = item.review!;\n const location = review.line !== null ? `${review.path}:${review.line}` : review.path;\n const parts = [`[PR review comment ${githubReviewCommentTs(review.commentId)} on ${location}]`];\n if (review.diffHunk) {\n const hunk =\n review.diffHunk.length > MAX_DIFF_HUNK_CHARS\n ? `…${review.diffHunk.slice(-MAX_DIFF_HUNK_CHARS)}`\n : review.diffHunk;\n parts.push(`\\`\\`\\`diff\\n${hunk}\\n\\`\\`\\``);\n }\n if (review.inReplyToId !== undefined) {\n const turns = await this.reviewThreadContext(item.ref, review.inReplyToId, review.commentId);\n if (turns.length > 0) {\n parts.push(`Thread so far:\\n${turns.join(\"\\n\")}`);\n }\n }\n parts.push(cleanedText);\n return parts.join(\"\\n\");\n }\n\n /**\n * Earlier turns of one review thread (root + replies before the trigger),\n * newest-truncated. Fail-soft: context is a nicety, the trigger is not.\n */\n private async reviewThreadContext(\n ref: GithubConversationRef,\n rootId: number,\n beforeId: number,\n ): Promise<string[]> {\n try {\n const all = await githubRetry(() =>\n this.client.listPullReviewComments(ref.owner, ref.repo, ref.number),\n );\n return all\n .filter(\n (comment) =>\n (comment.id === rootId || comment.in_reply_to_id === rootId) && comment.id < beforeId,\n )\n .slice(-MAX_THREAD_TURNS)\n .map((comment) => {\n const body =\n comment.body.length > MAX_THREAD_TURN_CHARS\n ? `${comment.body.slice(0, MAX_THREAD_TURN_CHARS)}…`\n : comment.body;\n return `@${comment.user.login}: ${body}`;\n });\n } catch (err) {\n log.logWarning(\n `GitHub: could not fetch review thread context for ${ref.owner}/${ref.repo}#${ref.number}`,\n err instanceof Error ? err.message : String(err),\n );\n return [];\n }\n }\n\n private async logIssueContext(\n ref: GithubConversationRef,\n conversationId: string,\n triggerCreatedAt: string,\n ): Promise<GithubIssue | null> {\n let issue: GithubIssue;\n try {\n issue = await githubRetry(() => this.client.getIssue(ref.owner, ref.repo, ref.number));\n } catch (err) {\n log.logWarning(\n `GitHub: could not fetch issue context for ${conversationId}`,\n err instanceof Error ? err.message : String(err),\n );\n return null;\n }\n // Dated just before the triggering comment, NOT issue.created_at: history\n // sync date-sorts entries and drops anything older than its recency\n // window, so an old issue's real creation date would silently evict the\n // one message that says what the thread is about.\n const triggerMs = Date.parse(triggerCreatedAt);\n const contextDate = new Date((Number.isFinite(triggerMs) ? triggerMs : Date.now()) - 1000);\n this.logToFile(conversationId, {\n date: contextDate.toISOString(),\n ts: GITHUB_ISSUE_BODY_TS,\n user: issue.user.login,\n userName: issue.user.login,\n text: `# ${issue.title}\\n\\n${issue.body ?? \"\"}`.trim(),\n attachments: [],\n isMessagingBot: false,\n });\n return issue;\n }\n\n // ==========================================================================\n // Repo clone\n // ==========================================================================\n\n /**\n * Clone the conversation's repo into its dir (bind-mounted into the\n * sandbox) using an ephemeral contents:read token that never leaves the\n * host. Non-fatal: a failed clone degrades to the pre-clone experience.\n */\n private async ensureRepoClone(\n ref: GithubConversationRef,\n conversationId: string,\n isPr: boolean,\n ): Promise<void> {\n const dir = conversationRepoDir(this.config.workingDir, conversationId);\n if (existsSync(dir)) return;\n try {\n const token = await this.client.createScopedInstallationToken(ref.repo, {\n contents: \"read\",\n });\n const prHeadBranch = isPr ? await fetchPrHeadBranch(this.client, ref) : undefined;\n await cloneRepo({\n url: `https://github.com/${ref.owner}/${ref.repo}.git`,\n dir,\n token,\n botLogin: `${this.appSlug}[bot]`,\n botEmail: this.botEmail ?? `${this.appSlug}[bot]@users.noreply.github.com`,\n prNumber: isPr ? ref.number : undefined,\n prHeadBranch,\n });\n log.logInfo(\n `[${conversationId}] Cloned ${ref.owner}/${ref.repo}${isPr ? ` and checked out PR #${ref.number} head as ${prHeadBranch ?? `pr-${ref.number}`}` : \"\"}`,\n );\n } catch (err) {\n log.logWarning(\n `GitHub: repo clone failed for ${conversationId}`,\n err instanceof Error ? err.message : String(err),\n );\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"bot.js","sourceRoot":"","sources":["../../../src/adapters/github/bot.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,IAAI,CAAC;AAChC,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AACrC,OAAO,EAAE,IAAI,EAAE,MAAM,mBAAmB,CAAC;AACzC,OAAO,EACL,uBAAuB,GAKxB,MAAM,kBAAkB,CAAC;AAC1B,OAAO,KAAK,GAAG,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C,MAAM,EAAE,EAAE,CAAC,CAAC,CAAC,EAAE,EAAE,CACvJ,CAAC;QACJ,CAAC;QAAC,OAAO,GAAG,EAAE,CAAC;YACb,GAAG,CAAC,UAAU,CACZ,iCAAiC,cAAc,EAAE,EACjD,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CACjD,CAAC;QACJ,CAAC;IACH,CAAC;CACF","sourcesContent":["import { existsSync } from \"fs\";\nimport { dirname, join } from \"path\";\nimport { Type } from \"@sinclair/typebox\";\nimport {\n createConversationEvent,\n type ConversationEvent,\n MessagingBot,\n MessagingEventHandler,\n MessagingInfo,\n} from \"../../adapter.js\";\nimport * as log from \"../../log.js\";\nimport { ensureDirExists, readJsonSchemaFileIfExists } from \"../../utils/file-guards.js\";\nimport { atomicWritePrivateFile } from \"../../utils/fs-atomic.js\";\nimport { resolveChatSessionKey } from \"../../sessions/policy.js\";\nimport {\n appendBotResponseLog,\n appendChannelLog,\n MessagingEventQueue,\n splitText,\n} from \"../shared.js\";\nimport { processMessageIntake } from \"../intake.js\";\nimport { GithubClient, GITHUB_MAX_COMMENT_LENGTH, githubRetry } from \"./client.js\";\nimport { createGithubAdapters } from \"./context.js\";\nimport { fetchIsPr, fetchPrHeadBranch, GithubOps } from \"./github-ops.js\";\nimport { cloneRepo, conversationRepoDir } from \"./repo.js\";\nimport { conversationOfficeDir, createOfficeAddress } from \"../../office-address.js\";\nimport { ensureOfficeDir } from \"../../office-registry.js\";\nimport {\n buildGithubConversationId,\n GITHUB_ISSUE_BODY_TS,\n githubReviewCommentTs,\n parseGithubConversationId,\n parseReviewCommentTs,\n} from \"./ids.js\";\nimport type {\n GithubBotConfig,\n GithubConversationRef,\n GithubEvent,\n GithubIssue,\n GithubReactionContent,\n GithubRepoRef,\n GithubSyncState,\n} from \"./types.js\";\n\nconst SyncStateSchema = Type.Object({\n repos: Type.Record(\n Type.String(),\n Type.Object({\n baseline: Type.String(),\n cursor: Type.String(),\n seenComments: Type.Array(Type.Number()),\n seenIssues: Type.Array(Type.Number()),\n // Optional: state files written before review-comment polling must keep\n // loading — a schema failure re-baselines and silently drops dedup state.\n seenReviewComments: Type.Optional(Type.Array(Type.Number())),\n }),\n ),\n});\n\n/**\n * Re-fetch this far behind the cursor each poll. Dedup is by id (the\n * watermark), so the overlap only costs bandwidth and closes the boundary\n * races of a bare `since` timestamp (DESIGN.md § Event source).\n */\nconst POLL_OVERLAP_MS = 5 * 60 * 1000;\n\nconst MAX_SEEN_IDS = 5000;\n\n/** Effective role → rank, for the trigger-permission gate. */\nconst PERMISSION_RANK: Record<string, number> = {\n none: 0,\n read: 1,\n triage: 2,\n write: 3,\n maintain: 4,\n admin: 5,\n};\n\n/**\n * Commenters need write or better to trigger the agent. Fixed, not a config\n * knob: it guards public repos (anyone can comment there), and the people who\n * ask an agent to change code are exactly the people with push access.\n */\nconst REQUIRED_TRIGGER_RANK = PERMISSION_RANK.write;\n\n/** Permission lookups are cached this long per repo+user. */\nconst PERMISSION_CACHE_TTL_MS = 5 * 60 * 1000;\n\n/** In-memory form of one repo's persisted watermark. */\ninterface RepoWatermark {\n baseline: string;\n cursor: string;\n seenComments: Set<number>;\n seenIssues: Set<number>;\n seenReviewComments: Set<number>;\n}\n\nexport const formatGithubContinuation = (partNum: number): string => `*(continued ${partNum})*`;\n\n/** Slack-style emoji short names → GitHub reaction content values. */\nconst GITHUB_REACTIONS: Record<string, GithubReactionContent> = {\n \"+1\": \"+1\",\n thumbsup: \"+1\",\n \"-1\": \"-1\",\n thumbsdown: \"-1\",\n laugh: \"laugh\",\n smile: \"laugh\",\n confused: \"confused\",\n heart: \"heart\",\n hooray: \"hooray\",\n tada: \"hooray\",\n rocket: \"rocket\",\n eyes: \"eyes\",\n};\n\ninterface IncomingItem {\n ref: GithubConversationRef;\n /** Comment id, rc-<id> for review comments, or GITHUB_ISSUE_BODY_TS for the body. */\n ts: string;\n user: string;\n text: string;\n createdAt: string;\n /** Known only for issue-body items; comment first-contact resolves it via getIssue. */\n isPr?: boolean;\n /** Present for inline PR review comments: the diff anchor to inject as context. */\n review?: {\n commentId: number;\n path: string;\n line: number | null;\n diffHunk: string;\n inReplyToId?: number;\n };\n}\n\n// Repo refs are lowercased at every entry point (env config here, the\n// installation API in start()) so conversation ids and sync-state keys never\n// depend on how a repo's name was spelled — GitHub is case-insensitive.\nfunction parseRepoList(repos: string[]): GithubRepoRef[] {\n return repos.map((entry) => {\n const [owner, repo, ...rest] = entry.split(\"/\");\n if (!owner || !repo || rest.length > 0) {\n throw new Error(`Invalid GITHUB_REPOS entry (expected owner/repo): ${entry}`);\n }\n return { owner: owner.toLowerCase(), repo: repo.toLowerCase() };\n });\n}\n\n/** Sets iterate in insertion order; drop the oldest ids once over the cap. */\nfunction pruneSeen(seen: Set<number>): void {\n if (seen.size <= MAX_SEEN_IDS) return;\n let toDrop = seen.size - MAX_SEEN_IDS / 2;\n for (const id of seen) {\n if (toDrop-- <= 0) break;\n seen.delete(id);\n }\n}\n\n/** Issue number from a comment's `issue_url` (…/repos/o/r/issues/42). */\nfunction issueNumberFromUrl(issueUrl: string): number {\n const match = /\\/issues\\/(\\d+)$/.exec(issueUrl);\n if (!match) {\n throw new Error(`Cannot parse issue number from ${issueUrl}`);\n }\n return Number(match[1]);\n}\n\n/** PR number from a review comment's `pull_request_url` (…/repos/o/r/pulls/42). */\nfunction prNumberFromUrl(pullRequestUrl: string): number {\n const match = /\\/pulls\\/(\\d+)$/.exec(pullRequestUrl);\n if (!match) {\n throw new Error(`Cannot parse PR number from ${pullRequestUrl}`);\n }\n return Number(match[1]);\n}\n\n/** Keep the tail: a review comment anchors to the hunk's final lines. */\nconst MAX_DIFF_HUNK_CHARS = 1500;\nconst MAX_THREAD_TURNS = 10;\nconst MAX_THREAD_TURN_CHARS = 500;\n\nexport class GithubMessagingBot implements MessagingBot {\n private readonly client: GithubClient;\n private readonly handler: MessagingEventHandler;\n private readonly config: GithubBotConfig;\n /** Host-side backend for the github_* tool pack; standalone from polling. */\n readonly ops: GithubOps;\n private appSlug: string | null = null;\n private botEmail: string | null = null;\n private watchedRepos: GithubRepoRef[] = [];\n private queues = new Map<string, MessagingEventQueue>();\n private repoState = new Map<string, RepoWatermark>();\n private permissionCache = new Map<string, { rank: number; expiresAt: number }>();\n private pollInFlight = false;\n\n constructor(handler: MessagingEventHandler, config: GithubBotConfig, client?: GithubClient) {\n this.handler = handler;\n this.config = config;\n this.client =\n client ??\n new GithubClient({\n appId: config.appId,\n privateKey: config.privateKey,\n installationId: config.installationId,\n });\n this.ops = new GithubOps(this.client, {\n workingDir: config.workingDir,\n cloudBuild: config.cloudBuild,\n });\n }\n\n // ==========================================================================\n // Public API (implements MessagingBot)\n // ==========================================================================\n\n async start(): Promise<void> {\n this.appSlug = await this.client.getAppSlug();\n // Canonical noreply author email (<user-id>+<login>@users.noreply.github.com)\n // so the bot's commits link to its avatar/profile; degrade to a plain\n // noreply spelling when the lookup fails.\n try {\n const botUserId = await this.client.getUserId(`${this.appSlug}[bot]`);\n this.botEmail = `${botUserId}+${this.appSlug}[bot]@users.noreply.github.com`;\n } catch {\n this.botEmail = `${this.appSlug}[bot]@users.noreply.github.com`;\n }\n this.watchedRepos =\n this.config.repos.length > 0\n ? parseRepoList(this.config.repos)\n : (await this.client.listInstallationRepositories()).map((repository) => ({\n owner: repository.owner.login.toLowerCase(),\n repo: repository.name.toLowerCase(),\n }));\n if (this.watchedRepos.length === 0) {\n log.logWarning(\"GitHub: installation has no repositories; nothing to poll\");\n }\n\n // Restore persisted watermarks; a repo watched for the first time gets a\n // baseline of \"now\" so history never triggers (DESIGN.md § Event source).\n const persisted = this.loadSyncState();\n const now = new Date().toISOString();\n for (const repo of this.watchedRepos) {\n const repoKey = `${repo.owner}/${repo.repo}`;\n const saved = persisted?.repos[repoKey];\n this.repoState.set(\n repoKey,\n saved\n ? {\n baseline: saved.baseline,\n cursor: saved.cursor,\n seenComments: new Set(saved.seenComments),\n seenIssues: new Set(saved.seenIssues),\n seenReviewComments: new Set(saved.seenReviewComments ?? []),\n }\n : {\n baseline: now,\n cursor: now,\n seenComments: new Set(),\n seenIssues: new Set(),\n seenReviewComments: new Set(),\n },\n );\n }\n this.persistSyncState();\n\n setInterval(() => {\n void this.poll();\n }, this.config.pollIntervalMs).unref();\n\n log.logConnected(\"GitHub\");\n log.logInfo(\n `GitHub bot started as @${this.appSlug}[bot], polling ${this.watchedRepos.length} repo(s) every ${Math.round(this.config.pollIntervalMs / 1000)}s`,\n );\n }\n\n async postMessage(channel: string, text: string): Promise<string> {\n const ref = parseGithubConversationId(channel);\n const parts = splitText(text, GITHUB_MAX_COMMENT_LENGTH, formatGithubContinuation);\n const firstId = await this.postComment(ref, parts[0]);\n for (const part of parts.slice(1)) {\n await this.postComment(ref, part);\n }\n return String(firstId);\n }\n\n async updateMessage(channel: string, ts: string, text: string): Promise<void> {\n const ref = parseGithubConversationId(channel);\n await githubRetry(() => this.client.updateIssueComment(ref.owner, ref.repo, Number(ts), text));\n }\n\n async addReaction(channel: string, messageTs: string, emoji: string): Promise<void> {\n const ref = parseGithubConversationId(channel);\n const content = GITHUB_REACTIONS[emoji.replace(/^:|:$/g, \"\")];\n if (!content) {\n throw new Error(\n `GitHub does not support reaction '${emoji}' (supported: ${Object.keys(GITHUB_REACTIONS).join(\", \")})`,\n );\n }\n const reviewCommentId = parseReviewCommentTs(messageTs);\n await githubRetry(() => {\n if (messageTs === GITHUB_ISSUE_BODY_TS) {\n return this.client.createIssueReaction(ref.owner, ref.repo, ref.number, content);\n }\n if (reviewCommentId !== null) {\n return this.client.createReviewCommentReaction(\n ref.owner,\n ref.repo,\n reviewCommentId,\n content,\n );\n }\n return this.client.createCommentReaction(ref.owner, ref.repo, Number(messageTs), content);\n });\n }\n\n enqueueEvent(event: ConversationEvent): boolean {\n const conversationId = event.conversationId;\n const queue = this.getQueue(conversationId);\n if (queue.size() >= 5) {\n log.logWarning(\n `Event queue full for ${conversationId}, discarding: ${event.text.substring(0, 50)}`,\n );\n return false;\n }\n log.logInfo(`Enqueueing event for ${conversationId}: ${event.text.substring(0, 50)}`);\n queue.enqueue(() => {\n const context = createGithubAdapters(event as GithubEvent, this);\n return this.handler.handleEvent(event, this, context);\n });\n return true;\n }\n\n getMessagingInfo(): MessagingInfo {\n return {\n name: \"github\",\n trustModel: \"open-trigger\",\n formattingGuide:\n \"## GitHub Formatting (GitHub Flavored Markdown)\\n\" +\n \"Standard Markdown plus tables, task lists, fenced code blocks, and ```suggestion blocks.\\n\" +\n \"Reference issues/PRs as #123 and users as @login (mentions notify people — use sparingly).\",\n channels: [],\n users: [],\n };\n }\n\n // ==========================================================================\n // Internal helpers (used by context.ts)\n // ==========================================================================\n\n async postComment(ref: GithubConversationRef, text: string): Promise<number> {\n const comment = await githubRetry(() =>\n this.client.createIssueComment(ref.owner, ref.repo, ref.number, text),\n );\n return comment.id;\n }\n\n async deleteComment(ref: GithubConversationRef, commentId: number): Promise<void> {\n await githubRetry(() => this.client.deleteIssueComment(ref.owner, ref.repo, commentId));\n }\n\n logToFile(conversationId: string, entry: object): void {\n appendChannelLog(this.config.workingDir, createOfficeAddress(\"github\", conversationId), entry);\n }\n\n logBotResponse(conversationId: string, text: string, ts: string): void {\n appendBotResponseLog(\n this.config.workingDir,\n createOfficeAddress(\"github\", conversationId),\n text,\n ts,\n );\n }\n\n // ==========================================================================\n // Private - polling\n // ==========================================================================\n\n private getQueue(conversationId: string): MessagingEventQueue {\n let queue = this.queues.get(conversationId);\n if (!queue) {\n queue = new MessagingEventQueue(\"GitHub\");\n this.queues.set(conversationId, queue);\n }\n return queue;\n }\n\n /** One poll tick over every watched repo. Public for tests. */\n async poll(): Promise<void> {\n if (this.pollInFlight) return;\n this.pollInFlight = true;\n try {\n let changed = false;\n for (const repo of this.watchedRepos) {\n try {\n changed = (await this.pollRepo(repo)) || changed;\n } catch (err) {\n log.logWarning(\n `GitHub poll failed for ${repo.owner}/${repo.repo}`,\n err instanceof Error ? err.message : String(err),\n );\n }\n }\n if (changed) {\n this.persistSyncState();\n }\n } finally {\n this.pollInFlight = false;\n }\n }\n\n private async pollRepo(repo: GithubRepoRef): Promise<boolean> {\n const repoKey = `${repo.owner}/${repo.repo}`;\n const state = this.repoState.get(repoKey);\n if (!state) return false;\n const since = new Date(Date.parse(state.cursor) - POLL_OVERLAP_MS).toISOString();\n let changed = false;\n\n // Comment activity also bumps the parent issue's updated_at, so the issues\n // list mostly echoes the comments list; only issues *created* since the\n // baseline are new conversations (their body is the first message).\n const issues = (await this.client.listIssuesSince(repo.owner, repo.repo, since)) ?? [];\n changed =\n (await this.advanceFeed(state, state.seenIssues, issues, (issue) => ({\n ref: { ...repo, number: issue.number },\n ts: GITHUB_ISSUE_BODY_TS,\n user: issue.user.login,\n text: `# ${issue.title}\\n\\n${issue.body ?? \"\"}`.trim(),\n createdAt: issue.created_at,\n isPr: Boolean(issue.pull_request),\n }))) || changed;\n\n const comments = (await this.client.listIssueCommentsSince(repo.owner, repo.repo, since)) ?? [];\n changed =\n (await this.advanceFeed(state, state.seenComments, comments, (comment) => ({\n ref: { ...repo, number: issueNumberFromUrl(comment.issue_url) },\n ts: String(comment.id),\n user: comment.user.login,\n text: comment.body,\n createdAt: comment.created_at,\n }))) || changed;\n\n // Inline PR review comments live in their own endpoint and id space; the\n // same watermark discipline applies. The bot's own thread replies (the\n // github_review_reply tool) re-surface here and are dropped as Bot-authored.\n const reviewComments =\n (await this.client.listPullReviewCommentsSince(repo.owner, repo.repo, since)) ?? [];\n changed =\n (await this.advanceFeed(state, state.seenReviewComments, reviewComments, (comment) => ({\n ref: { ...repo, number: prNumberFromUrl(comment.pull_request_url) },\n ts: githubReviewCommentTs(comment.id),\n user: comment.user.login,\n text: comment.body,\n createdAt: comment.created_at,\n isPr: true,\n review: {\n commentId: comment.id,\n path: comment.path,\n line: comment.line,\n diffHunk: comment.diff_hunk,\n inReplyToId: comment.in_reply_to_id,\n },\n }))) || changed;\n\n pruneSeen(state.seenComments);\n pruneSeen(state.seenIssues);\n pruneSeen(state.seenReviewComments);\n return changed;\n }\n\n /**\n * One feed's watermark advance — the same discipline for all three feeds:\n * bump the cursor on any fresher updated_at, then let the id watermark plus\n * the creation baseline decide what actually triggers (edits re-surface old\n * items with a fresh updated_at). Bot-authored items advance the watermark\n * without triggering.\n */\n private async advanceFeed<\n T extends {\n id: number;\n created_at: string;\n updated_at: string;\n user: { login: string; type: string };\n },\n >(\n state: RepoWatermark,\n seen: Set<number>,\n items: T[],\n toIncoming: (item: T) => IncomingItem,\n ): Promise<boolean> {\n let changed = false;\n for (const item of items) {\n if (item.updated_at > state.cursor) {\n state.cursor = item.updated_at;\n changed = true;\n }\n if (item.created_at < state.baseline || seen.has(item.id)) continue;\n seen.add(item.id);\n changed = true;\n if (item.user.type === \"Bot\") continue;\n await this.handleIncoming(toIncoming(item));\n }\n return changed;\n }\n\n // ==========================================================================\n // Private - watermark persistence\n // ==========================================================================\n\n private loadSyncState(): GithubSyncState | undefined {\n try {\n return readJsonSchemaFileIfExists(\n this.config.syncStatePath,\n SyncStateSchema,\n (detail) => `Malformed GitHub sync state at ${this.config.syncStatePath}: ${detail}`,\n );\n } catch (err) {\n // A bad state file re-baselines (history won't trigger) rather than\n // blocking startup; the next persist overwrites it.\n log.logWarning(\n \"GitHub: ignoring unreadable sync state\",\n err instanceof Error ? err.message : String(err),\n );\n return undefined;\n }\n }\n\n /** The persisted form of the current watermarks; the test/inspection surface. */\n syncStateSnapshot(): GithubSyncState {\n const state: GithubSyncState = { repos: {} };\n for (const [repoKey, watermark] of this.repoState) {\n state.repos[repoKey] = {\n baseline: watermark.baseline,\n cursor: watermark.cursor,\n seenComments: [...watermark.seenComments],\n seenIssues: [...watermark.seenIssues],\n seenReviewComments: [...watermark.seenReviewComments],\n };\n }\n return state;\n }\n\n private persistSyncState(): void {\n ensureDirExists(dirname(this.config.syncStatePath));\n atomicWritePrivateFile(this.config.syncStatePath, JSON.stringify(this.syncStateSnapshot()));\n }\n\n // ==========================================================================\n // Private - triggering\n // ==========================================================================\n\n /** Fresh regex per call: the `g` flag makes `test`/`replace` stateful. */\n private mentionPattern(): RegExp | null {\n return this.appSlug ? new RegExp(`@${this.appSlug}(?![\\\\w-])`, \"gi\") : null;\n }\n\n private isMentioned(text: string): boolean {\n const pattern = this.mentionPattern();\n return pattern ? pattern.test(text) : false;\n }\n\n private stripMention(text: string): string {\n const pattern = this.mentionPattern();\n return (pattern ? text.replace(pattern, \"\") : text).trim();\n }\n\n private isParticipating(conversationId: string): boolean {\n return existsSync(\n join(\n conversationOfficeDir(\n this.config.workingDir,\n createOfficeAddress(\"github\", conversationId),\n ),\n \"log.jsonl\",\n ),\n );\n }\n\n /**\n * True when `user` holds at least write permission on the repo. Fails\n * closed: a failed lookup denies the trigger (and logs) rather than\n * letting an unverified commenter drive the agent.\n */\n private async hasTriggerPermission(ref: GithubConversationRef, user: string): Promise<boolean> {\n const cacheKey = `${ref.owner}/${ref.repo}#${user}`;\n const cached = this.permissionCache.get(cacheKey);\n if (cached && Date.now() < cached.expiresAt) {\n return cached.rank >= REQUIRED_TRIGGER_RANK;\n }\n let rank: number;\n try {\n const role = await githubRetry(() =>\n this.client.getCollaboratorPermission(ref.owner, ref.repo, user),\n );\n // Custom role_name values are unrankable; the legacy permission field\n // still carries their closest standard mapping, so take the stronger.\n rank = Math.max(\n PERMISSION_RANK[role.role_name ?? \"\"] ?? 0,\n PERMISSION_RANK[role.permission] ?? 0,\n );\n } catch (err) {\n log.logWarning(\n `GitHub: permission lookup failed for ${user} on ${ref.owner}/${ref.repo}; denying trigger`,\n err instanceof Error ? err.message : String(err),\n );\n return false;\n }\n this.permissionCache.set(cacheKey, {\n rank,\n expiresAt: Date.now() + PERMISSION_CACHE_TTL_MS,\n });\n return rank >= REQUIRED_TRIGGER_RANK;\n }\n\n private async handleIncoming(item: IncomingItem): Promise<void> {\n const conversationId = buildGithubConversationId(item.ref);\n const mentioned = this.isMentioned(item.text);\n const participating = this.isParticipating(conversationId);\n // Narrow trigger (DESIGN.md): only threads the bot is mentioned in or\n // already participates in. Everything else is ignored without logging so\n // busy repos don't grow conversation dirs for untouched issues.\n if (!mentioned && !participating) return;\n\n // Permission gate: on public repos anyone can comment, so a mention from\n // anyone below write permission is ignored entirely (no log, no state).\n if (!(await this.hasTriggerPermission(item.ref, item.user))) {\n log.logInfo(\n `GitHub: ignoring ${conversationId} comment from ${item.user} (below write permission)`,\n );\n return;\n }\n\n const cleanedText = this.stripMention(item.text);\n const sessionKey = resolveChatSessionKey({\n conversationId,\n conversationKind: \"shared\",\n messageId: item.ts,\n persistentTopLevel: true,\n });\n\n const messageText = item.review\n ? await this.formatReviewMessage(item, cleanedText)\n : cleanedText;\n\n const eventBase = createConversationEvent({\n platform: \"github\",\n type: item.ts === GITHUB_ISSUE_BODY_TS ? \"issue\" : \"message\",\n conversationId,\n conversationKind: \"shared\",\n ts: item.ts,\n sessionKey,\n user: item.user,\n userName: item.user,\n text: messageText,\n }) as GithubEvent;\n\n await processMessageIntake({\n eventBase,\n workingDir: this.config.workingDir,\n isAutoReplyCandidate: false,\n // Match on the user-typed text, not the review-decorated messageText.\n magicWord: { text: cleanedText, addressed: mentioned, scopeFallback: \"never\" },\n busyPolicy: \"queue\",\n logEntryBase: {\n date: item.createdAt,\n ts: item.ts,\n user: item.user,\n userName: item.user,\n text: messageText,\n isMessagingBot: false,\n },\n log: (entry) => this.logToFile(conversationId, entry),\n // GitHub has no attachments; the prep hook is used to lay down the\n // issue context and repo clone only for messages that will dispatch,\n // and before the comment itself is logged.\n processAttachments: async () => {\n await this.prepareConversation(item, conversationId, participating);\n return [];\n },\n queueKey: conversationId,\n enqueue: (queueKey, work) => this.getQueue(queueKey).enqueue(work),\n handler: this.handler,\n bot: this,\n createContext: (event) => createGithubAdapters(event, this),\n });\n }\n\n /**\n * First contact: log the issue title/body ahead of the comment so the\n * session history starts with what the thread is about. The clone is\n * (re)attempted on every trigger while ./repo is missing — a no-op once\n * it exists — so a failed first clone (e.g. App permissions granted\n * later) heals on the next mention instead of wedging the conversation.\n */\n private async prepareConversation(\n item: IncomingItem,\n conversationId: string,\n participating: boolean,\n ): Promise<void> {\n let isPrHint = item.isPr;\n if (!participating && item.ts !== GITHUB_ISSUE_BODY_TS) {\n const issue = await this.logIssueContext(item.ref, conversationId, item.createdAt);\n // Only comments arrive without the PR-ness hint; review comments carry\n // isPr: true (they only exist on PRs) and that knowledge is authoritative.\n if (issue && isPrHint === undefined) isPrHint = Boolean(issue.pull_request);\n }\n if (!existsSync(conversationRepoDir(this.config.workingDir, conversationId))) {\n const isPr = isPrHint ?? (await fetchIsPr(this.client, item.ref));\n await this.ensureRepoClone(item.ref, conversationId, isPr);\n }\n }\n\n /**\n * Decorates an inline review comment with its diff anchor and (for replies)\n * the thread's earlier turns, so the agent knows which code the feedback is\n * about without hunting through the PR. The rc-<id> in the header is what\n * github_review_reply takes to answer in-thread.\n */\n private async formatReviewMessage(item: IncomingItem, cleanedText: string): Promise<string> {\n const review = item.review!;\n const location = review.line !== null ? `${review.path}:${review.line}` : review.path;\n const parts = [`[PR review comment ${githubReviewCommentTs(review.commentId)} on ${location}]`];\n if (review.diffHunk) {\n const hunk =\n review.diffHunk.length > MAX_DIFF_HUNK_CHARS\n ? `…${review.diffHunk.slice(-MAX_DIFF_HUNK_CHARS)}`\n : review.diffHunk;\n parts.push(`\\`\\`\\`diff\\n${hunk}\\n\\`\\`\\``);\n }\n if (review.inReplyToId !== undefined) {\n const turns = await this.reviewThreadContext(item.ref, review.inReplyToId, review.commentId);\n if (turns.length > 0) {\n parts.push(`Thread so far:\\n${turns.join(\"\\n\")}`);\n }\n }\n parts.push(cleanedText);\n return parts.join(\"\\n\");\n }\n\n /**\n * Earlier turns of one review thread (root + replies before the trigger),\n * newest-truncated. Fail-soft: context is a nicety, the trigger is not.\n */\n private async reviewThreadContext(\n ref: GithubConversationRef,\n rootId: number,\n beforeId: number,\n ): Promise<string[]> {\n try {\n const all = await githubRetry(() =>\n this.client.listPullReviewComments(ref.owner, ref.repo, ref.number),\n );\n return all\n .filter(\n (comment) =>\n (comment.id === rootId || comment.in_reply_to_id === rootId) && comment.id < beforeId,\n )\n .slice(-MAX_THREAD_TURNS)\n .map((comment) => {\n const body =\n comment.body.length > MAX_THREAD_TURN_CHARS\n ? `${comment.body.slice(0, MAX_THREAD_TURN_CHARS)}…`\n : comment.body;\n return `@${comment.user.login}: ${body}`;\n });\n } catch (err) {\n log.logWarning(\n `GitHub: could not fetch review thread context for ${ref.owner}/${ref.repo}#${ref.number}`,\n err instanceof Error ? err.message : String(err),\n );\n return [];\n }\n }\n\n private async logIssueContext(\n ref: GithubConversationRef,\n conversationId: string,\n triggerCreatedAt: string,\n ): Promise<GithubIssue | null> {\n let issue: GithubIssue;\n try {\n issue = await githubRetry(() => this.client.getIssue(ref.owner, ref.repo, ref.number));\n } catch (err) {\n log.logWarning(\n `GitHub: could not fetch issue context for ${conversationId}`,\n err instanceof Error ? err.message : String(err),\n );\n return null;\n }\n // Dated just before the triggering comment, NOT issue.created_at: history\n // sync date-sorts entries and drops anything older than its recency\n // window, so an old issue's real creation date would silently evict the\n // one message that says what the thread is about.\n const triggerMs = Date.parse(triggerCreatedAt);\n const contextDate = new Date((Number.isFinite(triggerMs) ? triggerMs : Date.now()) - 1000);\n this.logToFile(conversationId, {\n date: contextDate.toISOString(),\n ts: GITHUB_ISSUE_BODY_TS,\n user: issue.user.login,\n userName: issue.user.login,\n text: `# ${issue.title}\\n\\n${issue.body ?? \"\"}`.trim(),\n attachments: [],\n isMessagingBot: false,\n });\n return issue;\n }\n\n // ==========================================================================\n // Repo clone\n // ==========================================================================\n\n /**\n * Clone the conversation's repo into its dir (bind-mounted into the\n * sandbox) using an ephemeral contents:read token that never leaves the\n * host. Non-fatal: a failed clone degrades to the pre-clone experience.\n */\n private async ensureRepoClone(\n ref: GithubConversationRef,\n conversationId: string,\n isPr: boolean,\n ): Promise<void> {\n const dir = conversationRepoDir(this.config.workingDir, conversationId);\n if (existsSync(dir)) return;\n try {\n ensureOfficeDir(this.config.workingDir, createOfficeAddress(\"github\", conversationId));\n const token = await this.client.createScopedInstallationToken(ref.repo, {\n contents: \"read\",\n });\n const prHeadBranch = isPr ? await fetchPrHeadBranch(this.client, ref) : undefined;\n await cloneRepo({\n url: `https://github.com/${ref.owner}/${ref.repo}.git`,\n dir,\n token,\n botLogin: `${this.appSlug}[bot]`,\n botEmail: this.botEmail ?? `${this.appSlug}[bot]@users.noreply.github.com`,\n prNumber: isPr ? ref.number : undefined,\n prHeadBranch,\n });\n log.logInfo(\n `[${conversationId}] Cloned ${ref.owner}/${ref.repo}${isPr ? ` and checked out PR #${ref.number} head as ${prHeadBranch ?? `pr-${ref.number}`}` : \"\"}`,\n );\n } catch (err) {\n log.logWarning(\n `GitHub: repo clone failed for ${conversationId}`,\n err instanceof Error ? err.message : String(err),\n );\n }\n }\n}\n"]}
|
|
@@ -1,7 +1,8 @@
|
|
|
1
|
-
import type
|
|
1
|
+
import { type ConversationMessage, ConversationResponder, MessagingInfo } from "../../adapter.js";
|
|
2
2
|
import { type GithubMessagingBot } from "./bot.js";
|
|
3
3
|
import type { GithubEvent } from "./types.js";
|
|
4
4
|
export declare function createGithubAdapters(event: GithubEvent, bot: GithubMessagingBot): {
|
|
5
|
+
address: import("../../adapter.js").OfficeAddress;
|
|
5
6
|
message: ConversationMessage;
|
|
6
7
|
responder: ConversationResponder;
|
|
7
8
|
platform: MessagingInfo;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"context.d.ts","sourceRoot":"","sources":["../../../src/adapters/github/context.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,
|
|
1
|
+
{"version":3,"file":"context.d.ts","sourceRoot":"","sources":["../../../src/adapters/github/context.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,KAAK,mBAAmB,EACxB,qBAAqB,EACrB,aAAa,EACd,MAAM,kBAAkB,CAAC;AAG1B,OAAO,EAA4B,KAAK,kBAAkB,EAAE,MAAM,UAAU,CAAC;AAG7E,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAE9C,wBAAgB,oBAAoB,CAClC,KAAK,EAAE,WAAW,EAClB,GAAG,EAAE,kBAAkB,GACtB;IACD,OAAO,EAAE,OAAO,kBAAkB,EAAE,aAAa,CAAC;IAClD,OAAO,EAAE,mBAAmB,CAAC;IAC7B,SAAS,EAAE,qBAAqB,CAAC;IACjC,QAAQ,EAAE,aAAa,CAAC;CACzB,CAmGA"}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { createConversationMessage, } from "../../adapter.js";
|
|
1
2
|
import { resolveChatSessionKey } from "../../sessions/policy.js";
|
|
2
3
|
import { createProgressiveRenderer, formatMarkdownToolResult } from "../progressive-renderer.js";
|
|
3
4
|
import { formatGithubContinuation } from "./bot.js";
|
|
@@ -6,7 +7,10 @@ import { parseGithubConversationId } from "./ids.js";
|
|
|
6
7
|
export function createGithubAdapters(event, bot) {
|
|
7
8
|
const conversationId = event.conversationId;
|
|
8
9
|
const ref = parseGithubConversationId(conversationId);
|
|
9
|
-
const message = {
|
|
10
|
+
const message = createConversationMessage({
|
|
11
|
+
platform: "github",
|
|
12
|
+
conversationId,
|
|
13
|
+
address: event.address,
|
|
10
14
|
id: event.ts,
|
|
11
15
|
sessionKey: event.sessionKey ??
|
|
12
16
|
resolveChatSessionKey({
|
|
@@ -22,8 +26,7 @@ export function createGithubAdapters(event, bot) {
|
|
|
22
26
|
text: event.text,
|
|
23
27
|
attachments: event.attachments,
|
|
24
28
|
threadTs: event.thread_ts,
|
|
25
|
-
};
|
|
26
|
-
// The bot's getMessagingInfo() is the single authority for platform info;
|
|
29
|
+
});
|
|
27
30
|
// the conversation-scoped context below is an explicit append, not a fork.
|
|
28
31
|
const baseInfo = bot.getMessagingInfo();
|
|
29
32
|
const platform = {
|
|
@@ -93,6 +96,6 @@ export function createGithubAdapters(event, bot) {
|
|
|
93
96
|
uploadFallbackNote: (name) => `*(file \`${name}\` was produced, but the GitHub adapter cannot attach files to comments)*`,
|
|
94
97
|
react: (emoji) => bot.addReaction(conversationId, event.ts, emoji),
|
|
95
98
|
});
|
|
96
|
-
return { message, responder, platform };
|
|
99
|
+
return { address: message.address, message, responder, platform };
|
|
97
100
|
}
|
|
98
101
|
//# sourceMappingURL=context.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"context.js","sourceRoot":"","sources":["../../../src/adapters/github/context.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"context.js","sourceRoot":"","sources":["../../../src/adapters/github/context.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,yBAAyB,GAI1B,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAE,qBAAqB,EAAE,MAAM,0BAA0B,CAAC;AACjE,OAAO,EAAE,yBAAyB,EAAE,wBAAwB,EAAE,MAAM,4BAA4B,CAAC;AACjG,OAAO,EAAE,wBAAwB,EAA2B,MAAM,UAAU,CAAC;AAC7E,OAAO,EAAE,yBAAyB,EAAE,MAAM,aAAa,CAAC;AACxD,OAAO,EAAE,yBAAyB,EAAE,MAAM,UAAU,CAAC;AAGrD,MAAM,UAAU,oBAAoB,CAClC,KAAkB,EAClB,GAAuB;IAOvB,MAAM,cAAc,GAAG,KAAK,CAAC,cAAc,CAAC;IAC5C,MAAM,GAAG,GAAG,yBAAyB,CAAC,cAAc,CAAC,CAAC;IAEtD,MAAM,OAAO,GAAG,yBAAyB,CAAC;QACxC,QAAQ,EAAE,QAAQ;QAClB,cAAc;QACd,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,EAAE,EAAE,KAAK,CAAC,EAAE;QACZ,UAAU,EACR,KAAK,CAAC,UAAU;YAChB,qBAAqB,CAAC;gBACpB,cAAc;gBACd,gBAAgB,EAAE,KAAK,CAAC,gBAAgB;gBACxC,SAAS,EAAE,KAAK,CAAC,EAAE;gBACnB,kBAAkB,EAAE,IAAI;gBACxB,QAAQ,EAAE,KAAK,CAAC,SAAS;aAC1B,CA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AAC,CAAC;IAEH,OAAO,EAAE,OAAO,EAAE,OAAO,CAAC,OAAO,EAAE,OAAO,EAAE,SAAS,EAAE,QAAQ,EAAE,CAAC;AACpE,CAAC","sourcesContent":["import {\n createConversationMessage,\n type ConversationMessage,\n ConversationResponder,\n MessagingInfo,\n} from \"../../adapter.js\";\nimport { resolveChatSessionKey } from \"../../sessions/policy.js\";\nimport { createProgressiveRenderer, formatMarkdownToolResult } from \"../progressive-renderer.js\";\nimport { formatGithubContinuation, type GithubMessagingBot } from \"./bot.js\";\nimport { GITHUB_MAX_COMMENT_LENGTH } from \"./client.js\";\nimport { parseGithubConversationId } from \"./ids.js\";\nimport type { GithubEvent } from \"./types.js\";\n\nexport function createGithubAdapters(\n event: GithubEvent,\n bot: GithubMessagingBot,\n): {\n address: import(\"../../adapter.js\").OfficeAddress;\n message: ConversationMessage;\n responder: ConversationResponder;\n platform: MessagingInfo;\n} {\n const conversationId = event.conversationId;\n const ref = parseGithubConversationId(conversationId);\n\n const message = createConversationMessage({\n platform: \"github\",\n conversationId,\n address: event.address,\n id: event.ts,\n sessionKey:\n event.sessionKey ??\n resolveChatSessionKey({\n conversationId,\n conversationKind: event.conversationKind,\n messageId: event.ts,\n persistentTopLevel: true,\n threadTs: event.thread_ts,\n }),\n conversationKind: event.conversationKind,\n userId: event.user,\n userName: event.userName,\n text: event.text,\n attachments: event.attachments,\n threadTs: event.thread_ts,\n });\n // the conversation-scoped context below is an explicit append, not a fork.\n const baseInfo = bot.getMessagingInfo();\n const platform: MessagingInfo = {\n ...baseInfo,\n formattingGuide:\n `${baseInfo.formattingGuide}\\n\\n` +\n `## Conversation context\\n` +\n `This conversation IS GitHub issue/PR ${ref.owner}/${ref.repo}#${ref.number}: the ` +\n `first message in the history is its title and body, and the following messages are ` +\n `its comments. When the user says \"this issue\", they mean #${ref.number}. Messages ` +\n `tagged [PR review comment rc-<id> …] are inline review threads on a diff line: ` +\n `answer those with the github_review_reply tool (comment_id = that id) so the reply ` +\n `lands in-thread — your normal response posts as a plain PR comment.\\n\\n` +\n `## Repository & pull requests\\n` +\n `The repository is cloned at ./repo — a snapshot from this conversation's first ` +\n `trigger; run github_sync when it may be stale to pull the latest PR head or base ` +\n `branch. If this conversation is a pull request, its head branch is checked out ` +\n `under its real name (run git branch --show-current in ./repo to see it; fork PRs ` +\n `fall back to pr-${ref.number}). You have no git credentials, so git fetch/push ` +\n `fail by design.\\n` +\n `To ship code changes: commit inside ./repo (the git author is preconfigured) on a ` +\n `pi/<name> branch, then call the github_pr tool to push it. When this conversation's ` +\n `checked-out PR head branch is already named pi/<name> — e.g. a PR you opened ` +\n `earlier — commit directly on it and pass that branch to github_pr: the push ` +\n `updates THIS pull request instead of opening a new one. Any other branch opens a ` +\n `new pull request (draft: true for a draft); calling github_pr again with the same ` +\n `branch pushes new commits to its existing PR. Use github_checks to read CI results ` +\n `for your branch (or this PR) — pass a failing check's job id to read its log — and ` +\n `iterate until they pass. You cannot push the default branch or ` +\n `merge — humans review and merge every PR.\\n` +\n `github_read looks up PR/issue metadata this clone cannot show (diff stats, changed ` +\n `files, review state, other issues in this repo); github_issue manages labels, ` +\n `assignees, and close/reopen for triage.`,\n diagnostics: {\n showUsageSummary: false,\n },\n };\n\n // streaming: false — GitHub gets the finished response in one comment.\n // Streaming would edit the comment on every flush: API churn and \"edited\"\n // noise for readers who refresh rather than watch typing. There is also no\n // typing indicator or working suffix; progress shows through comment edits.\n const { responder } = createProgressiveRenderer({\n label: \"GitHub\",\n maxLength: GITHUB_MAX_COMMENT_LENGTH,\n formatContinuation: formatGithubContinuation,\n errorPrefix: \"**Error:** \",\n formatToolResult: formatMarkdownToolResult,\n logIntermediateResponses: true,\n responseErrorContext: (responseId) => ({\n platform: \"github\",\n conversationId,\n messageId: message.id,\n sessionKey: message.sessionKey,\n responseMessageId: responseId === null ? null : Number(responseId),\n conversationKind: message.conversationKind,\n }),\n post: async (text) => {\n return String(await bot.postComment(ref, text));\n },\n update: (id, text) => bot.updateMessage(conversationId, id, text),\n postExtra: async (text) => bot.postComment(ref, text),\n delete: async (id) => {\n await bot.deleteComment(ref, Number(id));\n },\n logBotResponse: (text, id) => bot.logBotResponse(conversationId, text, id),\n // The REST API cannot attach files to comments (uploads are a browser\n // feature); leave a pointer instead of failing the run.\n uploadFallbackNote: (name) =>\n `*(file \\`${name}\\` was produced, but the GitHub adapter cannot attach files to comments)*`,\n react: (emoji) => bot.addReaction(conversationId, event.ts, emoji),\n });\n\n return { address: message.address, message, responder, platform };\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"repo.d.ts","sourceRoot":"","sources":["../../../src/adapters/github/repo.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"repo.d.ts","sourceRoot":"","sources":["../../../src/adapters/github/repo.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EACV,gBAAgB,EAChB,iBAAiB,EACjB,eAAe,EACf,cAAc,EACf,MAAM,YAAY,CAAC;AAMpB;;;;GAIG;AACH,eAAO,MAAM,0BAA0B,QAAwC,CAAC;AAEhF,mFAAmF;AACnF,wBAAgB,mBAAmB,CAAC,UAAU,EAAE,MAAM,EAAE,cAAc,EAAE,MAAM,GAAG,MAAM,CAKtF;AA0CD;;;;;;GAMG;AACH,wBAAsB,SAAS,CAAC,OAAO,EAAE,gBAAgB,GAAG,OAAO,CAAC,IAAI,CAAC,CAkBxE;AAED;;;;;;;GAOG;AACH,wBAAsB,QAAQ,CAAC,OAAO,EAAE,eAAe,GAAG,OAAO,CAAC,cAAc,CAAC,CA8ChF;AAED;;;GAGG;AACH,wBAAsB,UAAU,CAAC,OAAO,EAAE,iBAAiB,GAAG,OAAO,CAAC,IAAI,CAAC,CAa1E"}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { execFile } from "child_process";
|
|
2
2
|
import { join } from "path";
|
|
3
|
+
import { conversationOfficeDir, createOfficeAddress } from "../../office-address.js";
|
|
3
4
|
import { promisify } from "util";
|
|
4
5
|
const execFileAsync = promisify(execFile);
|
|
5
6
|
const GIT_TIMEOUT_MS = 120_000;
|
|
@@ -11,7 +12,7 @@ const GIT_TIMEOUT_MS = 120_000;
|
|
|
11
12
|
export const GITHUB_PUSH_BRANCH_PATTERN = /^pi\/[A-Za-z0-9._][A-Za-z0-9._/-]*$/;
|
|
12
13
|
/** The conversation's clone location (bind-mounted into the sandbox as ./repo). */
|
|
13
14
|
export function conversationRepoDir(workingDir, conversationId) {
|
|
14
|
-
return join(workingDir, conversationId, "repo");
|
|
15
|
+
return join(conversationOfficeDir(workingDir, createOfficeAddress("github", conversationId)), "repo");
|
|
15
16
|
}
|
|
16
17
|
/**
|
|
17
18
|
* Pass the ephemeral token as a per-invocation header, never in the remote
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"repo.js","sourceRoot":"","sources":["../../../src/adapters/github/repo.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AACzC,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAC5B,OAAO,EAAE,SAAS,EAAE,MAAM,MAAM,CAAC;AAQjC,MAAM,aAAa,GAAG,SAAS,CAAC,QAAQ,CAAC,CAAC;AAE1C,MAAM,cAAc,GAAG,OAAO,CAAC;AAE/B;;;;GAIG;AACH,MAAM,CAAC,MAAM,0BAA0B,GAAG,qCAAqC,CAAC;AAEhF,mFAAmF;AACnF,MAAM,UAAU,mBAAmB,CAAC,UAAkB,EAAE,cAAsB;IAC5E,OAAO,IAAI,CAAC,UAAU,EAAE,cAAc,EAAE,MAAM,CAAC,CAAC;AAClD,CAAC;AAED;;;;GAIG;AACH,SAAS,WAAW,CAAC,KAAa;IAChC,MAAM,KAAK,GAAG,MAAM,CAAC,IAAI,CAAC,kBAAkB,KAAK,EAAE,CAAC,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC;IACxE,OAAO,CAAC,IAAI,EAAE,yCAAyC,KAAK,EAAE,CAAC,CAAC;AAClE,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nimport { promisify } from \"util\";\nimport type {\n CloneRepoOptions,\n PushBranchOptions,\n SyncRepoOptions,\n SyncRepoResult,\n} from \"./types.js\";\n\nconst execFileAsync = promisify(execFile);\n\nconst GIT_TIMEOUT_MS = 120_000;\n\n/**\n * Branches the bot may push: `pi/<name>`. Everything else — including the\n * repo's default branch by construction — is refused, so a driven agent can\n * only ever produce reviewable branches, never touch mainline directly.\n */\nexport const GITHUB_PUSH_BRANCH_PATTERN = /^pi\\/[A-Za-z0-9._][A-Za-z0-9._/-]*$/;\n\n/** The conversation's clone location (bind-mounted into the sandbox as ./repo). */\nexport function conversationRepoDir(workingDir: string, conversationId: string): string {\n return join(workingDir, conversationId, \"repo\");\n}\n\n/**\n * Pass the ephemeral token as a per-invocation header, never in the remote\n * URL: nothing credential-shaped may end up in `.git/config`, which lives in\n * the conversation dir and is bind-mounted into the sandbox.\n */\nfunction gitAuthArgs(token: string): string[] {\n const basic = Buffer.from(`x-access-token:${token}`).toString(\"base64\");\n return [\"-c\", `http.extraheader=Authorization: basic ${basic}`];\n}\n\nasync function git(args: string[], token?: string): Promise<string> {\n const { stdout } = await execFileAsync(\"git\", [...(token ? gitAuthArgs(token) : []), ...args], {\n timeout: GIT_TIMEOUT_MS,\n env: { ...process.env, GIT_TERMINAL_PROMPT: \"0\" },\n });\n return stdout;\n}\n\n/**\n * Git itself rejects these ref shapes; the check just keeps an API-supplied\n * branch name that would parse as a git option (leading dash) or an invalid\n * ref out of argv entirely instead of surfacing as a git error mid-clone.\n */\nfunction isSafeBranchName(name: string): boolean {\n return (\n name.length > 0 && !name.startsWith(\"-\") && !name.includes(\"..\") && !/[\\s~^:?*[\\\\]/.test(name)\n );\n}\n\n/**\n * Local checkout name for a PR conversation: the PR's real head branch when\n * known (same-repo heads only — the caller resolves that), falling back to\n * the synthetic `pr-<n>` for fork PRs, unresolvable heads, and unsafe names.\n * Using the real name is what lets the agent update the PR in place: commit\n * on a `pi/*` head and `github_pr` pushes back to the same branch.\n */\nfunction prCheckoutName(prNumber: number, prHeadBranch?: string): string {\n return prHeadBranch && isSafeBranchName(prHeadBranch) ? prHeadBranch : `pr-${prNumber}`;\n}\n\n/**\n * Shallow-clone a repo into a conversation dir and preconfigure the bot's\n * commit identity. For PR conversations, additionally fetch the PR head and\n * check it out so the agent starts on the code under review — under its real\n * branch name when the caller resolved one, which is what lets the agent push\n * fixes back to the PR itself.\n */\nexport async function cloneRepo(options: CloneRepoOptions): Promise<void> {\n await git([\"clone\", \"--depth\", \"50\", options.url, options.dir], options.token);\n await git([\"-C\", options.dir, \"config\", \"user.name\", options.botLogin]);\n await git([\"-C\", options.dir, \"config\", \"user.email\", options.botEmail]);\n if (options.prNumber !== undefined) {\n await git(\n [\"-C\", options.dir, \"fetch\", \"--depth\", \"50\", \"origin\", `pull/${options.prNumber}/head`],\n options.token,\n );\n await git([\n \"-C\",\n options.dir,\n \"checkout\",\n \"-B\",\n prCheckoutName(options.prNumber, options.prHeadBranch),\n \"FETCH_HEAD\",\n ]);\n }\n}\n\n/**\n * Refresh a conversation clone from origin. Always fetches; only moves the\n * checkout when that provably cannot lose agent work: the target branch is\n * the one checked out, the tree is clean, and it has no commits of its own\n * (`checkout -B` then handles fast-forward and force-pushed heads alike).\n * Anything else stays fetch-only — FETCH_HEAD is left for the agent, which\n * has full credential-less git inside the sandbox, to merge or rebase itself.\n */\nexport async function syncRepo(options: SyncRepoOptions): Promise<SyncRepoResult> {\n const { dir, token } = options;\n let refspec: string;\n let target: string;\n if (options.branch) {\n refspec = options.branch;\n target = options.branch;\n } else if (options.prNumber !== undefined) {\n refspec = `pull/${options.prNumber}/head`;\n target = prCheckoutName(options.prNumber, options.prHeadBranch);\n } else if (options.defaultBranch) {\n refspec = options.defaultBranch;\n target = options.defaultBranch;\n } else {\n throw new Error(\"syncRepo needs a branch, a PR number, or the default branch\");\n }\n\n await git([\"-C\", dir, \"fetch\", \"--depth\", \"50\", \"origin\", refspec], token);\n const fetchedSha = (await git([\"-C\", dir, \"rev-parse\", \"FETCH_HEAD\"])).trim();\n const dirty = (await git([\"-C\", dir, \"status\", \"--porcelain\"])).trim().length > 0;\n const currentBranch = (await git([\"-C\", dir, \"rev-parse\", \"--abbrev-ref\", \"HEAD\"])).trim();\n // Clones made before the head branch name was resolvable sit on the\n // synthetic pr-<n>; treat that as the same checkout so a clean sync\n // migrates them to the real name instead of going fetch-only forever.\n const legacyPrBranch = options.prNumber !== undefined ? `pr-${options.prNumber}` : undefined;\n const onTarget =\n currentBranch === target || (legacyPrBranch !== undefined && currentBranch === legacyPrBranch);\n let localCommits = 0;\n if (onTarget) {\n // Commits unique to HEAD split two ways: ones the agent committed here\n // (the clone's preconfigured bot identity) are its work and must survive;\n // ones committed by others were force-pushed away upstream and are safe\n // to drop. Filter by the bot committer so a rebased PR head still syncs.\n const botEmail = (await git([\"-C\", dir, \"config\", \"user.email\"])).trim();\n localCommits = Number(\n (\n await git([\"-C\", dir, \"rev-list\", \"--count\", `--committer=${botEmail}`, \"FETCH_HEAD..HEAD\"])\n ).trim(),\n );\n }\n\n const updatedCheckout = onTarget && !dirty && localCommits === 0;\n if (updatedCheckout) {\n await git([\"-C\", dir, \"checkout\", \"-B\", target, \"FETCH_HEAD\"]);\n }\n return { target, fetchedSha, updatedCheckout, dirty, currentBranch, localCommits };\n}\n\n/**\n * Push one local branch to origin. Non-force by construction (plain refspec),\n * and only `pi/*` branches are accepted.\n */\nexport async function pushBranch(options: PushBranchOptions): Promise<void> {\n const { dir, branch, token } = options;\n if (!GITHUB_PUSH_BRANCH_PATTERN.test(branch)) {\n throw new Error(\n `Refusing to push branch '${branch}': only branches matching pi/<name> may be pushed.`,\n );\n }\n try {\n await git([\"-C\", dir, \"rev-parse\", \"--verify\", \"--quiet\", `refs/heads/${branch}`]);\n } catch {\n throw new Error(`Branch '${branch}' does not exist in the conversation's ./repo clone.`);\n }\n await git([\"-C\", dir, \"push\", \"origin\", `refs/heads/${branch}:refs/heads/${branch}`], token);\n}\n"]}
|
|
1
|
+
{"version":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,YAAY,CAAC,CAAC,CAAC;IACjE,CAAC;IACD,OAAO,EAAE,MAAM,EAAE,UAAU,EAAE,eAAe,EAAE,KAAK,EAAE,aAAa,EAAE,YAAY,EAAE,CAAC;AACrF,CAAC;AAED;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,UAAU,CAAC,OAA0B;IACzD,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,GAAG,OAAO,CAAC;IACvC,IAAI,CAAC,0BAA0B,CAAC,IAAI,CAAC,MAAM,CAAC,EAAE,CAAC;QAC7C,MAAM,IAAI,KAAK,CACb,4BAA4B,MAAM,oDAAoD,CACvF,CAAC;IACJ,CAAC;IACD,IAAI,CAAC;QACH,MAAM,GAAG,CAAC,CAAC,IAAI,EAAE,GAAG,EAAE,WAAW,EAAE,UAAU,EAAE,SAAS,EAAE,cAAc,MAAM,EAAE,CAAC,CAAC,CAAC;IACrF,CAAC;IAAC,MAAM,CAAC;QACP,MAAM,IAAI,KAAK,CAAC,WAAW,MAAM,sDAAsD,CAAC,CAAC;IAC3F,CAAC;IACD,MAAM,GAAG,CAAC,CAAC,IAAI,EAAE,GAAG,EAAE,MAAM,EAAE,QAAQ,EAAE,cAAc,MAAM,eAAe,MAAM,EAAE,CAAC,EAAE,KAAK,CAAC,CAAC;AAC/F,CAAC","sourcesContent":["import { execFile } from \"child_process\";\nimport { join } from \"path\";\nimport { conversationOfficeDir, createOfficeAddress } from \"../../office-address.js\";\nimport { promisify } from \"util\";\nimport type {\n CloneRepoOptions,\n PushBranchOptions,\n SyncRepoOptions,\n SyncRepoResult,\n} from \"./types.js\";\n\nconst execFileAsync = promisify(execFile);\n\nconst GIT_TIMEOUT_MS = 120_000;\n\n/**\n * Branches the bot may push: `pi/<name>`. Everything else — including the\n * repo's default branch by construction — is refused, so a driven agent can\n * only ever produce reviewable branches, never touch mainline directly.\n */\nexport const GITHUB_PUSH_BRANCH_PATTERN = /^pi\\/[A-Za-z0-9._][A-Za-z0-9._/-]*$/;\n\n/** The conversation's clone location (bind-mounted into the sandbox as ./repo). */\nexport function conversationRepoDir(workingDir: string, conversationId: string): string {\n return join(\n conversationOfficeDir(workingDir, createOfficeAddress(\"github\", conversationId)),\n \"repo\",\n );\n}\n\n/**\n * Pass the ephemeral token as a per-invocation header, never in the remote\n * URL: nothing credential-shaped may end up in `.git/config`, which lives in\n * the conversation dir and is bind-mounted into the sandbox.\n */\nfunction gitAuthArgs(token: string): string[] {\n const basic = Buffer.from(`x-access-token:${token}`).toString(\"base64\");\n return [\"-c\", `http.extraheader=Authorization: basic ${basic}`];\n}\n\nasync function git(args: string[], token?: string): Promise<string> {\n const { stdout } = await execFileAsync(\"git\", [...(token ? gitAuthArgs(token) : []), ...args], {\n timeout: GIT_TIMEOUT_MS,\n env: { ...process.env, GIT_TERMINAL_PROMPT: \"0\" },\n });\n return stdout;\n}\n\n/**\n * Git itself rejects these ref shapes; the check just keeps an API-supplied\n * branch name that would parse as a git option (leading dash) or an invalid\n * ref out of argv entirely instead of surfacing as a git error mid-clone.\n */\nfunction isSafeBranchName(name: string): boolean {\n return (\n name.length > 0 && !name.startsWith(\"-\") && !name.includes(\"..\") && !/[\\s~^:?*[\\\\]/.test(name)\n );\n}\n\n/**\n * Local checkout name for a PR conversation: the PR's real head branch when\n * known (same-repo heads only — the caller resolves that), falling back to\n * the synthetic `pr-<n>` for fork PRs, unresolvable heads, and unsafe names.\n * Using the real name is what lets the agent update the PR in place: commit\n * on a `pi/*` head and `github_pr` pushes back to the same branch.\n */\nfunction prCheckoutName(prNumber: number, prHeadBranch?: string): string {\n return prHeadBranch && isSafeBranchName(prHeadBranch) ? prHeadBranch : `pr-${prNumber}`;\n}\n\n/**\n * Shallow-clone a repo into a conversation dir and preconfigure the bot's\n * commit identity. For PR conversations, additionally fetch the PR head and\n * check it out so the agent starts on the code under review — under its real\n * branch name when the caller resolved one, which is what lets the agent push\n * fixes back to the PR itself.\n */\nexport async function cloneRepo(options: CloneRepoOptions): Promise<void> {\n await git([\"clone\", \"--depth\", \"50\", options.url, options.dir], options.token);\n await git([\"-C\", options.dir, \"config\", \"user.name\", options.botLogin]);\n await git([\"-C\", options.dir, \"config\", \"user.email\", options.botEmail]);\n if (options.prNumber !== undefined) {\n await git(\n [\"-C\", options.dir, \"fetch\", \"--depth\", \"50\", \"origin\", `pull/${options.prNumber}/head`],\n options.token,\n );\n await git([\n \"-C\",\n options.dir,\n \"checkout\",\n \"-B\",\n prCheckoutName(options.prNumber, options.prHeadBranch),\n \"FETCH_HEAD\",\n ]);\n }\n}\n\n/**\n * Refresh a conversation clone from origin. Always fetches; only moves the\n * checkout when that provably cannot lose agent work: the target branch is\n * the one checked out, the tree is clean, and it has no commits of its own\n * (`checkout -B` then handles fast-forward and force-pushed heads alike).\n * Anything else stays fetch-only — FETCH_HEAD is left for the agent, which\n * has full credential-less git inside the sandbox, to merge or rebase itself.\n */\nexport async function syncRepo(options: SyncRepoOptions): Promise<SyncRepoResult> {\n const { dir, token } = options;\n let refspec: string;\n let target: string;\n if (options.branch) {\n refspec = options.branch;\n target = options.branch;\n } else if (options.prNumber !== undefined) {\n refspec = `pull/${options.prNumber}/head`;\n target = prCheckoutName(options.prNumber, options.prHeadBranch);\n } else if (options.defaultBranch) {\n refspec = options.defaultBranch;\n target = options.defaultBranch;\n } else {\n throw new Error(\"syncRepo needs a branch, a PR number, or the default branch\");\n }\n\n await git([\"-C\", dir, \"fetch\", \"--depth\", \"50\", \"origin\", refspec], token);\n const fetchedSha = (await git([\"-C\", dir, \"rev-parse\", \"FETCH_HEAD\"])).trim();\n const dirty = (await git([\"-C\", dir, \"status\", \"--porcelain\"])).trim().length > 0;\n const currentBranch = (await git([\"-C\", dir, \"rev-parse\", \"--abbrev-ref\", \"HEAD\"])).trim();\n // Clones made before the head branch name was resolvable sit on the\n // synthetic pr-<n>; treat that as the same checkout so a clean sync\n // migrates them to the real name instead of going fetch-only forever.\n const legacyPrBranch = options.prNumber !== undefined ? `pr-${options.prNumber}` : undefined;\n const onTarget =\n currentBranch === target || (legacyPrBranch !== undefined && currentBranch === legacyPrBranch);\n let localCommits = 0;\n if (onTarget) {\n // Commits unique to HEAD split two ways: ones the agent committed here\n // (the clone's preconfigured bot identity) are its work and must survive;\n // ones committed by others were force-pushed away upstream and are safe\n // to drop. Filter by the bot committer so a rebased PR head still syncs.\n const botEmail = (await git([\"-C\", dir, \"config\", \"user.email\"])).trim();\n localCommits = Number(\n (\n await git([\"-C\", dir, \"rev-list\", \"--count\", `--committer=${botEmail}`, \"FETCH_HEAD..HEAD\"])\n ).trim(),\n );\n }\n\n const updatedCheckout = onTarget && !dirty && localCommits === 0;\n if (updatedCheckout) {\n await git([\"-C\", dir, \"checkout\", \"-B\", target, \"FETCH_HEAD\"]);\n }\n return { target, fetchedSha, updatedCheckout, dirty, currentBranch, localCommits };\n}\n\n/**\n * Push one local branch to origin. Non-force by construction (plain refspec),\n * and only `pi/*` branches are accepted.\n */\nexport async function pushBranch(options: PushBranchOptions): Promise<void> {\n const { dir, branch, token } = options;\n if (!GITHUB_PUSH_BRANCH_PATTERN.test(branch)) {\n throw new Error(\n `Refusing to push branch '${branch}': only branches matching pi/<name> may be pushed.`,\n );\n }\n try {\n await git([\"-C\", dir, \"rev-parse\", \"--verify\", \"--quiet\", `refs/heads/${branch}`]);\n } catch {\n throw new Error(`Branch '${branch}' does not exist in the conversation's ./repo clone.`);\n }\n await git([\"-C\", dir, \"push\", \"origin\", `refs/heads/${branch}:refs/heads/${branch}`], token);\n}\n"]}
|
package/dist/adapters/intake.js
CHANGED
|
@@ -46,7 +46,7 @@ export async function processMessageIntake(options) {
|
|
|
46
46
|
}
|
|
47
47
|
async function rejectedWhileBusy() {
|
|
48
48
|
const sessionKey = options.eventBase.sessionKey ?? options.eventBase.conversationId;
|
|
49
|
-
if (!options.handler.isRunning(sessionKey))
|
|
49
|
+
if (!options.handler.isRunning(options.eventBase.address, sessionKey))
|
|
50
50
|
return false;
|
|
51
51
|
await options.bot.postMessage(options.eventBase.conversationId, formatAlreadyWorking(options.bot, "/stop"));
|
|
52
52
|
return true;
|
|
@@ -79,14 +79,15 @@ export async function processMessageIntake(options) {
|
|
|
79
79
|
*/
|
|
80
80
|
async function handleStopMagicWord(options) {
|
|
81
81
|
const { handler, bot, eventBase, magicWord } = options;
|
|
82
|
+
const address = eventBase.address;
|
|
82
83
|
const conversationId = eventBase.conversationId;
|
|
83
84
|
const sessionKey = eventBase.sessionKey;
|
|
84
|
-
let target = resolveStopTarget({ handler,
|
|
85
|
+
let target = resolveStopTarget({ handler, address, sessionKey });
|
|
85
86
|
if (!target && widensToScopedSession(magicWord.scopeFallback, sessionKey, conversationId)) {
|
|
86
|
-
target = resolveOnlyScopedStopTarget(handler,
|
|
87
|
+
target = resolveOnlyScopedStopTarget(handler, address);
|
|
87
88
|
}
|
|
88
89
|
if (target) {
|
|
89
|
-
await handler.handleStop(
|
|
90
|
+
await handler.handleStop(address, target, bot);
|
|
90
91
|
}
|
|
91
92
|
else if (magicWord.addressed) {
|
|
92
93
|
await bot.postMessage(conversationId, formatNothingRunning(bot));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"intake.js","sourceRoot":"","sources":["../../src/adapters/intake.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,qCAAqC,EACrC,oBAAoB,GACrB,MAAM,4BAA4B,CAAC;AAEpC,OAAO,EAAE,oBAAoB,EAAE,oBAAoB,EAAE,MAAM,yBAAyB,CAAC;AACrF,OAAO,EAAE,uBAAuB,EAAE,MAAM,eAAe,CAAC;AACxD,OAAO,EAAE,2BAA2B,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAG7E;;;;GAIG;AACH,MAAM,UAAU,cAAc,CAAC,IAAY;IACzC,OAAO,qBAAqB,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC;AACjE,CAAC;AAED;;;;;;;;;;;GAWG;AACH,MAAM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AAS,CAAC,cAAc,CAAC;IAChD,MAAM,UAAU,GAAG,SAAS,CAAC,UAAU,CAAC;IAExC,IAAI,MAAM,GAAG,iBAAiB,CAAC,EAAE,OAAO,EAAE,OAAO,EAAE,UAAU,EAAE,CAAC,CAAC;IACjE,IAAI,CAAC,MAAM,IAAI,qBAAqB,CAAC,SAAS,CAAC,aAAa,EAAE,UAAU,EAAE,cAAc,CAAC,EAAE,CAAC;QAC1F,MAAM,GAAG,2BAA2B,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;IACzD,CAAC;IAED,IAAI,MAAM,EAAE,CAAC;QACX,MAAM,OAAO,CAAC,UAAU,CAAC,OAAO,EAAE,MAAM,EAAE,GAAG,CAAC,CAAC;IACjD,CAAC;SAAM,IAAI,SAAS,CAAC,SAAS,EAAE,CAAC;QAC/B,MAAM,GAAG,CAAC,WAAW,CAAC,cAAc,EAAE,oBAAoB,CAAC,GAAG,CAAC,CAAC,CAAC;IACnE,CAAC;AACH,CAAC;AAED,SAAS,qBAAqB,CAC5B,aAA+C,EAC/C,UAA8B,EAC9B,cAAsB;IAEtB,IAAI,aAAa,KAAK,OAAO;QAAE,OAAO,KAAK,CAAC;IAC5C,IAAI,aAAa,KAAK,QAAQ;QAAE,OAAO,IAAI,CAAC;IAC5C,2EAA2E;IAC3E,4EAA4E;IAC5E,OAAO,UAAU,KAAK,SAAS,IAAI,UAAU,KAAK,cAAc,CAAC;AACnE,CAAC","sourcesContent":["import {\n assertSessionKeyBelongsToConversation,\n assertConversationId,\n} from \"../sessions/session-key.js\";\nimport type { ConversationEvent } from \"../adapter.js\";\nimport { formatAlreadyWorking, formatNothingRunning } from \"../platform-messages.js\";\nimport { evaluateAutoReplyPolicy } from \"../trigger.js\";\nimport { resolveOnlyScopedStopTarget, resolveStopTarget } from \"./shared.js\";\nimport type { MessageIntakeOptions, MessageIntakeOutcome } from \"./types.js\";\n\n/**\n * Recognize a magic word: a highest-priority chat control phrase that bypasses\n * trigger policy and queueing (see CONTEXT.md). One grammar for every\n * platform: optional leading slash, optional `@botname` suffix, any case.\n */\nexport function matchMagicWord(text: string): \"stop\" | null {\n return /^\\/?stop(?:@\\w+)?$/i.test(text.trim()) ? \"stop\" : null;\n}\n\n/**\n * Shared message ingress pipeline for platform adapters.\n *\n * Platform adapters normalize SDK events; this module owns the ordering for\n * messages that may start an agent run:\n *\n * magic word → trigger policy → attachments → log → busy policy → queue → dispatch\n *\n * Magic words are matched before the trigger gate — `stop` must never wait on\n * an auto-reply judgment or queue behind a running agent turn. Adapters state\n * platform policy as data (`magicWord`, `busyPolicy`) instead of callbacks.\n */\nexport async function processMessageIntake<TEvent extends ConversationEvent>(\n options: MessageIntakeOptions<TEvent>,\n): Promise<MessageIntakeOutcome> {\n assertConversationId(options.eventBase.conversationId);\n if (options.eventBase.sessionKey !== undefined) {\n assertSessionKeyBelongsToConversation(\n options.eventBase.sessionKey,\n options.eventBase.conversationId,\n );\n }\n if (matchMagicWord(options.magicWord.text ?? options.eventBase.text) === \"stop\") {\n options.log?.({ ...options.logEntryBase, attachments: [] });\n await handleStopMagicWord(options);\n return \"magic-word\";\n }\n\n const triggerResult = options.isAutoReplyCandidate\n ? await evaluateAutoReplyPolicy({ event: options.eventBase, workingDir: options.workingDir })\n : ({ trigger: true, reason: \"addressed\" } as const);\n\n if (!triggerResult.trigger) {\n options.log?.({ ...options.logEntryBase, attachments: [] });\n return \"not-triggered\";\n }\n\n function prepareEvent(attachments: unknown[]): TEvent {\n const event = { ...options.eventBase, attachments } as TEvent;\n options.log?.({ ...options.logEntryBase, attachments });\n return event;\n }\n\n async function rejectedWhileBusy(): Promise<boolean> {\n const sessionKey = options.eventBase.sessionKey ?? options.eventBase.conversationId;\n if (!options.handler.isRunning(options.eventBase.address, sessionKey)) return false;\n await options.bot.postMessage(\n options.eventBase.conversationId,\n formatAlreadyWorking(options.bot, \"/stop\"),\n );\n return true;\n }\n\n function dispatch(event: TEvent): Promise<void> {\n const context = options.createContext(event);\n return options.handler.handleEvent(event, options.bot, context);\n }\n\n if (options.deferAttachmentsUntilRun) {\n // Busy rejection happens inside the queued work here, so the outcome is\n // already \"enqueued\" by the time it is evaluated.\n options.enqueue(options.queueKey, async () => {\n const event = prepareEvent(await options.processAttachments());\n if (options.busyPolicy === \"reject\" && (await rejectedWhileBusy())) return;\n return dispatch(event);\n });\n return \"enqueued\";\n }\n\n const event = prepareEvent(await options.processAttachments());\n if (options.busyPolicy === \"reject\" && (await rejectedWhileBusy())) return \"rejected-busy\";\n options.enqueue(options.queueKey, () => dispatch(event));\n return \"enqueued\";\n}\n\n/**\n * Resolve and stop the session a magic-word `stop` targets. When nothing is\n * running, reply only if the message addressed the bot — an unaddressed\n * \"stop\" in a busy channel should never make the bot pipe up.\n */\nasync function handleStopMagicWord<TEvent extends ConversationEvent>(\n options: MessageIntakeOptions<TEvent>,\n): Promise<void> {\n const { handler, bot, eventBase, magicWord } = options;\n const address = eventBase.address;\n const conversationId = eventBase.conversationId;\n const sessionKey = eventBase.sessionKey;\n\n let target = resolveStopTarget({ handler, address, sessionKey });\n if (!target && widensToScopedSession(magicWord.scopeFallback, sessionKey, conversationId)) {\n target = resolveOnlyScopedStopTarget(handler, address);\n }\n\n if (target) {\n await handler.handleStop(address, target, bot);\n } else if (magicWord.addressed) {\n await bot.postMessage(conversationId, formatNothingRunning(bot));\n }\n}\n\nfunction widensToScopedSession(\n scopeFallback: \"top-level\" | \"always\" | \"never\",\n sessionKey: string | undefined,\n conversationId: string,\n): boolean {\n if (scopeFallback === \"never\") return false;\n if (scopeFallback === \"always\") return true;\n // \"top-level\": only a message aimed at the persistent conversation session\n // may widen to the single running scoped session; thread messages stay put.\n return sessionKey === undefined || sessionKey === conversationId;\n}\n"]}
|