typeclaw 0.51.0 → 0.52.0
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/dist/types/agent/bash-sandbox-env.d.ts +2 -0
- package/dist/types/agent/bash-sandbox.d.ts +4 -0
- package/dist/types/agent/index.d.ts +5 -0
- package/dist/types/agent/multimodal/look-at.d.ts +1 -1
- package/dist/types/agent/plugin-tools.d.ts +4 -0
- package/dist/types/agent/prompt-cache-key.d.ts +1 -0
- package/dist/types/agent/session-tail.d.ts +12 -0
- package/dist/types/agent/subagents.d.ts +5 -0
- package/dist/types/agent/system-prompt-composition.d.ts +1 -0
- package/dist/types/agent/system-prompt.d.ts +2 -0
- package/dist/types/agent/tools/channel-disengage.d.ts +1 -1
- package/dist/types/agent/tools/channel-edit.d.ts +1 -1
- package/dist/types/agent/tools/channel-fetch-attachment.d.ts +1 -1
- package/dist/types/agent/tools/channel-handoff.d.ts +1 -1
- package/dist/types/agent/tools/channel-history.d.ts +1 -1
- package/dist/types/agent/tools/channel-react.d.ts +1 -1
- package/dist/types/agent/tools/channel-read.d.ts +10 -2
- package/dist/types/agent/tools/channel-reply.d.ts +1 -1
- package/dist/types/agent/tools/channel-send.d.ts +1 -1
- package/dist/types/agent/tools/channel-session-search.d.ts +1 -1
- package/dist/types/agent/tools/grant-role.d.ts +1 -1
- package/dist/types/agent/tools/post-github-review.d.ts +1 -1
- package/dist/types/agent/tools/restart.d.ts +1 -1
- package/dist/types/agent/tools/skip-response.d.ts +1 -1
- package/dist/types/agent/tools/spawn-subagent.d.ts +2 -1
- package/dist/types/agent/tools/stream-snapshot.d.ts +1 -1
- package/dist/types/agent/tools/subagent-cancel.d.ts +1 -1
- package/dist/types/agent/tools/subagent-output.d.ts +1 -1
- package/dist/types/agent/tools/todo/index.d.ts +1 -1
- package/dist/types/agent/tools/webfetch/adaptive-html.d.ts +3 -3
- package/dist/types/agent/tools/webfetch/strategies/readability-process.d.ts +48 -0
- package/dist/types/agent/tools/webfetch/tool.d.ts +2 -2
- package/dist/types/agent/tools/websearch.d.ts +1 -1
- package/dist/types/channels/adapters/github/auth-app.d.ts +25 -0
- package/dist/types/channels/adapters/github/auth-pat.d.ts +17 -0
- package/dist/types/channels/adapters/github/auth.d.ts +24 -0
- package/dist/types/channels/github-token-bridge.d.ts +4 -0
- package/dist/types/channels/lost-background-context.d.ts +2 -0
- package/dist/types/channels/persistence.d.ts +1 -0
- package/dist/types/channels/router.d.ts +5 -1
- package/dist/types/channels/types.d.ts +1 -0
- package/dist/types/coding-agent/tool.d.ts +1 -1
- package/dist/types/config/config.d.ts +20 -11
- package/dist/types/config/providers.d.ts +47 -0
- package/dist/types/eval/sandbox.d.ts +2 -0
- package/dist/types/git/resolve-identity.d.ts +2 -0
- package/dist/types/init/dockerfile.d.ts +1 -0
- package/dist/types/init/gitignore.d.ts +1 -1
- package/dist/types/permissions/builtins.d.ts +1 -0
- package/dist/types/plugin/types.d.ts +3 -0
- package/dist/types/sandbox/canonical-secrets.d.ts +2 -2
- package/dist/types/sandbox/coding-agent.d.ts +1 -1
- package/dist/types/sandbox/dependency-bins.d.ts +1 -0
- package/dist/types/sandbox/dev-source.d.ts +2 -2
- package/dist/types/sandbox/hidden-paths.d.ts +1 -0
- package/dist/types/sandbox/index.d.ts +1 -1
- package/dist/types/sandbox/policy.d.ts +3 -0
- package/dist/types/typevault/cli-path.d.ts +2 -0
- package/dist/types/typevault/envelope-store.d.ts +11 -0
- package/dist/types/typevault/lifecycle.d.ts +13 -0
- package/dist/types/typevault/vault.d.ts +27 -0
- package/package.json +8 -7
- package/scripts/test.ts +252 -0
- package/src/agent/bash-sandbox-env.ts +33 -1
- package/src/agent/bash-sandbox.ts +20 -6
- package/src/agent/index.ts +120 -31
- package/src/agent/multimodal/look-at.ts +1 -1
- package/src/agent/plugin-tools.ts +35 -1
- package/src/agent/prompt-cache-key.ts +26 -3
- package/src/agent/session-origin.ts +39 -18
- package/src/agent/session-tail.ts +28 -0
- package/src/agent/subagents.ts +21 -2
- package/src/agent/system-prompt-composition.ts +18 -0
- package/src/agent/system-prompt.ts +39 -1
- package/src/agent/tool-error-remediation.ts +18 -3
- package/src/agent/tools/channel-disengage.ts +1 -1
- package/src/agent/tools/channel-edit.ts +1 -1
- package/src/agent/tools/channel-fetch-attachment.ts +1 -1
- package/src/agent/tools/channel-handoff.ts +3 -2
- package/src/agent/tools/channel-history.ts +2 -1
- package/src/agent/tools/channel-react.ts +1 -1
- package/src/agent/tools/channel-read.ts +36 -3
- package/src/agent/tools/channel-reply.ts +1 -1
- package/src/agent/tools/channel-send.ts +4 -3
- package/src/agent/tools/channel-session-search.ts +13 -4
- package/src/agent/tools/grant-role.ts +1 -1
- package/src/agent/tools/post-github-review.ts +1 -1
- package/src/agent/tools/restart.ts +1 -1
- package/src/agent/tools/skip-response.ts +1 -1
- package/src/agent/tools/spawn-subagent.ts +15 -1
- package/src/agent/tools/stream-snapshot.ts +1 -1
- package/src/agent/tools/subagent-cancel.ts +1 -1
- package/src/agent/tools/subagent-output.ts +1 -1
- package/src/agent/tools/todo/index.ts +1 -1
- package/src/agent/tools/webfetch/adaptive-html.ts +6 -4
- package/src/agent/tools/webfetch/strategies/readability-child.ts +25 -0
- package/src/agent/tools/webfetch/strategies/readability-process.ts +185 -0
- package/src/agent/tools/webfetch/tool.ts +6 -5
- package/src/agent/tools/websearch.ts +1 -1
- package/src/browser/dockerfile.ts +1 -1
- package/src/browser/fill-secret.ts +92 -35
- package/src/browser/registry.ts +6 -6
- package/src/bundled-plugins/agent-messenger-cli-auth/command.ts +211 -0
- package/src/bundled-plugins/agent-messenger-cli-auth/index.ts +186 -0
- package/src/bundled-plugins/backup/index.ts +17 -2
- package/src/bundled-plugins/backup/runner.ts +37 -2
- package/src/bundled-plugins/browser-agent/browser-agent.ts +51 -14
- package/src/bundled-plugins/browser-agent/index.ts +12 -5
- package/src/bundled-plugins/managed-browser/index.ts +25 -2
- package/src/bundled-plugins/managed-browser/skills/browserskill/browserskill/SKILL.md +13 -5
- package/src/bundled-plugins/managed-browser/skills/omowright/omowright/SKILL.md +56 -5
- package/src/bundled-plugins/memory/README.md +23 -2
- package/src/bundled-plugins/memory/append-fragment.ts +133 -0
- package/src/bundled-plugins/memory/append-tool.ts +80 -149
- package/src/bundled-plugins/memory/dreaming.ts +2 -0
- package/src/bundled-plugins/memory/index.ts +33 -6
- package/src/bundled-plugins/memory/memory-logger.ts +133 -11
- package/src/bundled-plugins/memory/references/store-reference-tool.ts +56 -32
- package/src/bundled-plugins/memory/remember-tool.ts +81 -0
- package/src/bundled-plugins/memory/search-tool-hybrid.ts +91 -0
- package/src/bundled-plugins/memory/search-tool.ts +58 -12
- package/src/bundled-plugins/memory/stream-events.ts +2 -0
- package/src/bundled-plugins/memory/transcript-cursor.ts +30 -0
- package/src/bundled-plugins/memory/transcript-preload.ts +131 -26
- package/src/bundled-plugins/memory/transcript-view.ts +36 -0
- package/src/bundled-plugins/memory/watermark.ts +19 -10
- package/src/bundled-plugins/reviewer/reviewer.ts +20 -0
- package/src/bundled-plugins/security/policies/outbound-secret-scan.ts +3 -6
- package/src/bundled-plugins/security/policies/outbound-text.ts +20 -0
- package/src/bundled-plugins/security/policies/system-prompt-leak.ts +2 -7
- package/src/bundled-plugins/typevault/grants.ts +119 -0
- package/src/bundled-plugins/typevault/index.ts +152 -0
- package/src/bundled-plugins/typevault/request.ts +87 -0
- package/src/bundled-plugins/typevault/runtime.ts +45 -0
- package/src/bundled-plugins/typevault/skills/typevault/SKILL.md +65 -0
- package/src/channels/adapter-halt.ts +17 -0
- package/src/channels/adapters/github/history.ts +23 -2
- package/src/channels/adapters/github/inbound.ts +60 -1
- package/src/channels/adapters/github/index.ts +27 -5
- package/src/channels/adapters/github/reconcile-open-prs.ts +7 -1
- package/src/channels/adapters/kakaotalk-author-resolver.ts +7 -5
- package/src/channels/adapters/kakaotalk-channel-resolver.ts +45 -15
- package/src/channels/adapters/kakaotalk-classify.ts +7 -9
- package/src/channels/adapters/kakaotalk-list.ts +62 -0
- package/src/channels/adapters/kakaotalk-member-cache.ts +67 -0
- package/src/channels/adapters/kakaotalk-membership.ts +27 -10
- package/src/channels/adapters/kakaotalk-mention.ts +61 -0
- package/src/channels/adapters/kakaotalk.ts +159 -125
- package/src/channels/adapters/teams-classify.ts +18 -8
- package/src/channels/github-token-bridge.ts +13 -0
- package/src/channels/lost-background-context.ts +46 -0
- package/src/channels/manager.ts +52 -3
- package/src/channels/persistence.ts +5 -0
- package/src/channels/router.ts +120 -21
- package/src/channels/schema.ts +1 -1
- package/src/channels/types.ts +3 -0
- package/src/coding-agent/tool.ts +1 -1
- package/src/config/config.ts +20 -1
- package/src/config/providers.ts +65 -0
- package/src/container/start.ts +15 -2
- package/src/doctor/channel-checks.ts +33 -0
- package/src/doctor/checks.ts +12 -2
- package/src/eval/sandbox.ts +3 -0
- package/src/eval/tool.ts +1 -0
- package/src/git/resolve-identity.ts +67 -2
- package/src/git/system-commit.ts +7 -0
- package/src/init/dockerfile.ts +5 -1
- package/src/init/gitignore.ts +3 -3
- package/src/init/index.ts +1 -0
- package/src/init/models-dev.ts +2 -0
- package/src/init/validate-api-key.ts +5 -0
- package/src/migrations/secrets-v1-to-v2.ts +2 -0
- package/src/permissions/builtins.ts +8 -0
- package/src/plugin/types.ts +6 -0
- package/src/run/bundled-plugins.ts +12 -0
- package/src/run/channel-session-factory.ts +3 -0
- package/src/run/index.ts +13 -2
- package/src/sandbox/build.ts +1 -0
- package/src/sandbox/canonical-secrets.ts +6 -0
- package/src/sandbox/dependency-bins.ts +13 -1
- package/src/sandbox/dev-source.ts +21 -12
- package/src/sandbox/hidden-paths.ts +1 -1
- package/src/sandbox/index.ts +1 -0
- package/src/sandbox/policy.ts +5 -0
- package/src/secrets/hydrate.ts +4 -1
- package/src/secrets/storage.ts +10 -1
- package/src/server/command-runner.ts +4 -0
- package/src/server/index.ts +8 -1
- package/src/skills/typeclaw-config/SKILL.md +16 -0
- package/src/skills/typeclaw-memory/SKILL.md +3 -1
- package/src/skills/typeclaw-permissions/SKILL.md +8 -8
- package/src/skills/typeclaw-troubleshooting/SKILL.md +18 -1
- package/src/tunnels/active.ts +14 -0
- package/src/typevault/bash-cli.ts +18 -0
- package/src/typevault/cli-path.ts +11 -0
- package/src/typevault/envelope-helper.ts +17 -0
- package/src/typevault/envelope-store.ts +98 -0
- package/src/typevault/lifecycle.ts +132 -0
- package/src/typevault/prompt-tunnel.ts +33 -0
- package/src/typevault/redaction.ts +37 -0
- package/src/typevault/vault.ts +283 -0
- package/typeclaw.schema.json +40 -10
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: typevault
|
|
3
|
+
description: Use secrets from this agent's TypeVault vault without putting them in the transcript. Use when a task needs an API key, password, token, OAuth credential, SSH key or TOTP code that lives in the vault or in a project's `.typevault/`, when asked to join a project's vault, or when the user mentions TypeVault, the vault, or storing a secret.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# TypeVault
|
|
7
|
+
|
|
8
|
+
This agent keeps secrets in its own TypeVault vault. The `typevault` command in your bash already holds a live grant for your role's tier and every tier below it (`owner` > `trusted` > `member` > `guest`), so you can use what your role may use without asking for a key. Every read is audited with your session.
|
|
9
|
+
|
|
10
|
+
## Rules
|
|
11
|
+
|
|
12
|
+
- **Never print a secret.** Use `typevault run` so values go into the child's environment and its output is redacted. Values your grant has read are also scrubbed from tool output, so a printed value shows up as `[redacted]`; that is not a bug to work around.
|
|
13
|
+
- **Never put a secret on the command line or in a file you then read.** Pass values on stdin.
|
|
14
|
+
- **Always give a `--reason`.** It is written to the audit trail.
|
|
15
|
+
- If a secret you need is not listed, your role cannot reach it, or nobody stored it yet. Tell the user; don't look for it elsewhere.
|
|
16
|
+
|
|
17
|
+
## Look around
|
|
18
|
+
|
|
19
|
+
```sh
|
|
20
|
+
typevault ls # entries your grant reaches
|
|
21
|
+
typevault whoami # your grant, its tiers and expiry
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
Entries are named `typevault://<service>[/<account>][#<field>]`, e.g. `typevault://openai`, `typevault://github/bot#password`.
|
|
25
|
+
|
|
26
|
+
## Use secrets
|
|
27
|
+
|
|
28
|
+
```sh
|
|
29
|
+
typevault run --only typevault://openai --reason "summarize the report" -- sh -c 'curl -H "Authorization: Bearer $OPENAI" https://api.openai.com/v1/models'
|
|
30
|
+
typevault run --only typevault://github/bot --reason "log in to GitHub" -- ./login.sh
|
|
31
|
+
DATABASE_URL=typevault://postgres/prod#url typevault run --reason "run migrations" -- bun run migrate
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
- Env names come from the entry name: `typevault://github/bot#password` -> `GITHUB_BOT_PASSWORD`, `typevault://openai` -> `OPENAI`. To choose the name, set a variable to a `typevault://` reference as above.
|
|
35
|
+
- Quote `$VAR` references in single quotes so your shell does not expand them before `run` sets them.
|
|
36
|
+
- `run` loads every entry of your own tier; entries from lower tiers load only when `--only` names them exactly.
|
|
37
|
+
- TOTP fields hold the current code, never the seed.
|
|
38
|
+
|
|
39
|
+
## A project's own vault
|
|
40
|
+
|
|
41
|
+
The `typevault` command always opens this agent's vault, even inside a project. For a project that keeps its own `.typevault/`, run the project's CLI from its checkout instead, e.g. `bun typevault ...` when the project depends on `typevault`. Your bash already holds this agent's machine identity for project vaults, so nothing asks for a password.
|
|
42
|
+
|
|
43
|
+
```sh
|
|
44
|
+
bun typevault join # prints the `typevault member add ...` line
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
Post that line to the user verbatim, in the chat they asked from, for a vault owner to run. It is not a secret: the `tvp1:` value is this identity's public keys only, so it carries no credential, and the vault rules above do not apply to it. Never withhold, redact or truncate it. Never use `join --name` or pick a password: the identity is already set up. Once they add you and push, pull and use the project's CLI (`bun typevault ls`, `bun typevault run ...`) with the same rules as above.
|
|
48
|
+
|
|
49
|
+
## Fill a web form
|
|
50
|
+
|
|
51
|
+
Call `browser_fill_secret` with a vault reference as `name` (e.g. `typevault://github/bot#password`) after focusing the field. The value is typed into the page and never comes back to you.
|
|
52
|
+
|
|
53
|
+
## Ask the user for a secret
|
|
54
|
+
|
|
55
|
+
When a secret you need is not in the vault, call `vault_request` with the entry name, a preset (`api_key`, `password`, ...) and a reason. Send the user the returned link **and** match code, and tell them to check the code on the page before submitting. Never ask them to paste a secret into chat. The value is stored in your role's tier when they submit; check with `typevault ls`.
|
|
56
|
+
|
|
57
|
+
If `vault_request` says the page has no public URL yet, its tunnel is still starting; try again in a moment.
|
|
58
|
+
|
|
59
|
+
## Store secrets
|
|
60
|
+
|
|
61
|
+
```sh
|
|
62
|
+
printf '%s' "$VALUE_FROM_ENV" | typevault set typevault://service/account --preset api_key --stdin
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
A secret is stored in your role's tier, so roles below yours cannot read it. Never type a secret value into a command yourself, even piped.
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
// An adapter throws this from start(), or reports it through haltReason(),
|
|
2
|
+
// when retrying with the same credentials cannot succeed and every retry is
|
|
3
|
+
// another login against the platform. Personal-account platforms (KakaoTalk)
|
|
4
|
+
// treat repeated rejected logins as abuse and escalate restrictions, so the
|
|
5
|
+
// manager must stop retrying instead of backing off forever. A halted adapter
|
|
6
|
+
// restarts only when its inputs change (credential rotation, config edit) or
|
|
7
|
+
// an operator restarts it explicitly.
|
|
8
|
+
export class ChannelAdapterHaltedError extends Error {
|
|
9
|
+
constructor(message: string) {
|
|
10
|
+
super(message)
|
|
11
|
+
this.name = 'ChannelAdapterHaltedError'
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export function isChannelAdapterHaltedError(err: unknown): err is ChannelAdapterHaltedError {
|
|
16
|
+
return err instanceof ChannelAdapterHaltedError
|
|
17
|
+
}
|
|
@@ -5,14 +5,35 @@ import type { GithubAuthContext } from './auth'
|
|
|
5
5
|
import { GITHUB_API_BASE, githubJsonHeaders } from './auth-pat'
|
|
6
6
|
import { parseChat, parseRepo } from './outbound'
|
|
7
7
|
|
|
8
|
+
// Repos that have delivered an inbound, per chat id. A chat id like `pr:12`
|
|
9
|
+
// exists in every repo, so a read names its repo explicitly; without one it
|
|
10
|
+
// resolves only when a single repo is known for that chat, never by recency,
|
|
11
|
+
// so one conversation's read can't land in another repo's thread.
|
|
12
|
+
export function createChatWorkspaceIndex() {
|
|
13
|
+
const workspacesByChat = new Map<string, Set<string>>()
|
|
14
|
+
return {
|
|
15
|
+
remember(workspace: string, chat: string): void {
|
|
16
|
+
const known = workspacesByChat.get(chat)
|
|
17
|
+
if (known === undefined) workspacesByChat.set(chat, new Set([workspace]))
|
|
18
|
+
else known.add(workspace)
|
|
19
|
+
},
|
|
20
|
+
resolve(chat: string, workspace?: string): string | null {
|
|
21
|
+
const known = workspacesByChat.get(chat)
|
|
22
|
+
if (known === undefined) return null
|
|
23
|
+
if (workspace !== undefined) return known.has(workspace) ? workspace : null
|
|
24
|
+
return known.size === 1 ? [...known][0]! : null
|
|
25
|
+
},
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
8
29
|
export function createGithubHistoryCallback(options: {
|
|
9
30
|
token: (context?: GithubAuthContext) => Promise<string>
|
|
10
|
-
workspaceForChat: (chat: string) => string | null
|
|
31
|
+
workspaceForChat: (chat: string, workspace?: string) => string | null
|
|
11
32
|
fetchImpl?: typeof fetch
|
|
12
33
|
}): HistoryCallback {
|
|
13
34
|
const fetchImpl = options.fetchImpl ?? fetch
|
|
14
35
|
return async (args: FetchHistoryArgs): Promise<FetchHistoryResult> => {
|
|
15
|
-
const workspace = options.workspaceForChat(args.chat)
|
|
36
|
+
const workspace = options.workspaceForChat(args.chat, args.workspace)
|
|
16
37
|
if (workspace === null)
|
|
17
38
|
return { ok: false, error: 'github history unavailable until this chat receives an inbound' }
|
|
18
39
|
const repo = parseRepo(workspace)
|
|
@@ -154,6 +154,22 @@ export async function processVerifiedGithubDelivery(
|
|
|
154
154
|
))
|
|
155
155
|
}
|
|
156
156
|
}
|
|
157
|
+
let staleRecoveredRemoval = false
|
|
158
|
+
// A recovered removal can arrive after a newer re-request was admitted. Applying it
|
|
159
|
+
// would cancel that request's check run and erase its pending replay entry.
|
|
160
|
+
if (input.recovered === true && eventAllowed && event === 'pull_request' && action === 'review_request_removed') {
|
|
161
|
+
const repository = readRepository(payload)
|
|
162
|
+
const prNumber = readNumber(readRecord(payload.pull_request), 'number')
|
|
163
|
+
if (repository !== null && prNumber !== null) {
|
|
164
|
+
staleRecoveredRemoval = await recoveredReviewerIsRequestedAgain(
|
|
165
|
+
options,
|
|
166
|
+
repository,
|
|
167
|
+
prNumber,
|
|
168
|
+
payload,
|
|
169
|
+
`${repository.owner}/${repository.name}`,
|
|
170
|
+
)
|
|
171
|
+
}
|
|
172
|
+
}
|
|
157
173
|
const isSynchronize = event === 'pull_request' && action === 'synchronize'
|
|
158
174
|
if (!isSynchronize && delivery !== '') {
|
|
159
175
|
if (options.dedup.has(delivery)) {
|
|
@@ -172,7 +188,7 @@ export async function processVerifiedGithubDelivery(
|
|
|
172
188
|
options.dedup.add(delivery)
|
|
173
189
|
}
|
|
174
190
|
|
|
175
|
-
if (!eventAllowed || staleRecoveredDraft) return
|
|
191
|
+
if (!eventAllowed || staleRecoveredDraft || staleRecoveredRemoval) return
|
|
176
192
|
|
|
177
193
|
// This control event must run before the self-author drop: a maintainer can
|
|
178
194
|
// draft the bot's PR, and the bot can draft its own PR. Either action must
|
|
@@ -230,6 +246,9 @@ export async function processVerifiedGithubDelivery(
|
|
|
230
246
|
if (event === 'pull_request' && action === 'review_request_removed') {
|
|
231
247
|
const prNumber = readNumber(readRecord(payload.pull_request), 'number')
|
|
232
248
|
if (prNumber !== null) {
|
|
249
|
+
// Withdrawn work must not survive in the pending log, or the next boot's
|
|
250
|
+
// pending replay reviews a PR nobody asked for anymore.
|
|
251
|
+
await options.clearPendingReview?.(classified.workspace, prNumber)
|
|
233
252
|
void githubReviewChecks.cancelPullRequest(classified.workspace, prNumber, 'the review request was removed')
|
|
234
253
|
}
|
|
235
254
|
}
|
|
@@ -386,6 +405,46 @@ async function recoveredPullRequestIsStillDraft(
|
|
|
386
405
|
}
|
|
387
406
|
}
|
|
388
407
|
|
|
408
|
+
async function recoveredReviewerIsRequestedAgain(
|
|
409
|
+
options: GithubWebhookHandlerOptions,
|
|
410
|
+
repository: { owner: string; name: string },
|
|
411
|
+
prNumber: number,
|
|
412
|
+
payload: Record<string, unknown>,
|
|
413
|
+
workspace: string,
|
|
414
|
+
): Promise<boolean> {
|
|
415
|
+
const removedLogin = readUser(payload.requested_reviewer)?.login ?? null
|
|
416
|
+
const removedTeam = readReviewerTeam(payload.requested_team)?.slug ?? null
|
|
417
|
+
if (removedLogin === null && removedTeam === null) return false
|
|
418
|
+
if (options.authToken === undefined) {
|
|
419
|
+
throw new Error(`recovered review request removal check unavailable for ${workspace}#${prNumber}: auth unavailable`)
|
|
420
|
+
}
|
|
421
|
+
try {
|
|
422
|
+
const token = await options.authToken({ repoSlug: workspace })
|
|
423
|
+
const response = await (options.fetchImpl ?? fetch)(
|
|
424
|
+
`${GITHUB_API_BASE}/repos/${repository.owner}/${repository.name}/pulls/${prNumber}/requested_reviewers`,
|
|
425
|
+
{ headers: githubJsonHeaders(token) },
|
|
426
|
+
)
|
|
427
|
+
if (!response.ok) {
|
|
428
|
+
throw new Error(`requested reviewers fetch returned ${response.status}`)
|
|
429
|
+
}
|
|
430
|
+
const current = readRecord(await response.json().catch(() => null))
|
|
431
|
+
if (!Array.isArray(current?.users) || !Array.isArray(current?.teams)) {
|
|
432
|
+
throw new Error('requested reviewers response missing users or teams')
|
|
433
|
+
}
|
|
434
|
+
const requestedAgain =
|
|
435
|
+
(removedLogin !== null && current.users.some((user) => readUser(user)?.login === removedLogin)) ||
|
|
436
|
+
(removedTeam !== null && current.teams.some((team) => readReviewerTeam(team)?.slug === removedTeam))
|
|
437
|
+
if (requestedAgain) {
|
|
438
|
+
options.logger.info(
|
|
439
|
+
`[github] recovered review request removal skipped for ${workspace}#${prNumber}: reviewer was requested again`,
|
|
440
|
+
)
|
|
441
|
+
}
|
|
442
|
+
return requestedAgain
|
|
443
|
+
} catch (err) {
|
|
444
|
+
throw new Error(`recovered review request removal check failed for ${workspace}#${prNumber}: ${describeError(err)}`)
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
|
|
389
448
|
function scheduleDraftAbort(input: {
|
|
390
449
|
workspace: string
|
|
391
450
|
prNumber: number
|
|
@@ -22,7 +22,7 @@ import { createGithubChannelNameResolver } from './channel-resolver'
|
|
|
22
22
|
import { createDeliveryDedup } from './dedup'
|
|
23
23
|
import { findPermissionGaps } from './event-permissions'
|
|
24
24
|
import { createGithubFetchAttachmentCallback } from './fetch-attachment'
|
|
25
|
-
import { createGithubHistoryCallback } from './history'
|
|
25
|
+
import { createChatWorkspaceIndex, createGithubHistoryCallback } from './history'
|
|
26
26
|
import { createGithubWebhookHandler, processVerifiedGithubDelivery, type GithubWebhookHandlerOptions } from './inbound'
|
|
27
27
|
import { readGithubLastAlive, writeGithubLastAlive } from './last-alive'
|
|
28
28
|
import { applyManagedPath, buildManagedPath, resolveAgentId } from './managed-path'
|
|
@@ -134,6 +134,16 @@ const MAX_RECOVERED_PER_SWEEP = 50
|
|
|
134
134
|
// durable cooldown store, so a tick is cheap when nothing new needs review.
|
|
135
135
|
const DEFAULT_RECONCILE_INTERVAL_MS = 30 * 60 * 1000
|
|
136
136
|
|
|
137
|
+
// Pending reviews admitted during this process, keyed by its router. A tunnel URL change
|
|
138
|
+
// rebuilds and restarts the adapter seconds after boot, but the router and the review
|
|
139
|
+
// turns it already admitted keep running. The boot replay exists for work an earlier
|
|
140
|
+
// process lost, so a later start in the same process must not admit that work again.
|
|
141
|
+
const pendingAdmissionsByRouter = new WeakMap<object, Set<string>>()
|
|
142
|
+
|
|
143
|
+
function pendingAdmissionKey(repo: string, prNumber: number, work: { headSha: string; kind: string }): string {
|
|
144
|
+
return `${canonicalGithubRepo(repo)}#${prNumber}@${work.headSha}:${work.kind}`
|
|
145
|
+
}
|
|
146
|
+
|
|
137
147
|
export function createGithubAdapter(options: GithubAdapterOptions): GithubAdapter {
|
|
138
148
|
const logger = options.logger ?? consoleLogger
|
|
139
149
|
const fetchImpl = options.fetchImpl ?? fetch
|
|
@@ -156,7 +166,10 @@ export function createGithubAdapter(options: GithubAdapterOptions): GithubAdapte
|
|
|
156
166
|
let stopObservingDismissals: (() => void) | null = null
|
|
157
167
|
let lifecycleGeneration = 0
|
|
158
168
|
let unregisterTokenBridge: (() => void) | null = null
|
|
159
|
-
|
|
169
|
+
let unregisterSelfBridge: (() => void) | null = null
|
|
170
|
+
const workspaceByChat = createChatWorkspaceIndex()
|
|
171
|
+
const pendingAdmissions = pendingAdmissionsByRouter.get(options.router) ?? new Set<string>()
|
|
172
|
+
pendingAdmissionsByRouter.set(options.router, pendingAdmissions)
|
|
160
173
|
const setIntervalFn =
|
|
161
174
|
options.setInterval ??
|
|
162
175
|
((handler: () => void, ms: number) => {
|
|
@@ -165,7 +178,7 @@ export function createGithubAdapter(options: GithubAdapterOptions): GithubAdapte
|
|
|
165
178
|
})
|
|
166
179
|
|
|
167
180
|
const rememberWorkspace = (workspace: string, chat: string): void => {
|
|
168
|
-
workspaceByChat.
|
|
181
|
+
workspaceByChat.remember(workspace, chat)
|
|
169
182
|
}
|
|
170
183
|
|
|
171
184
|
// Repo/owner-aware token resolver. A single GitHub App can span multiple
|
|
@@ -224,7 +237,7 @@ export function createGithubAdapter(options: GithubAdapterOptions): GithubAdapte
|
|
|
224
237
|
const history = createGithubHistoryCallback({
|
|
225
238
|
token: authToken,
|
|
226
239
|
fetchImpl,
|
|
227
|
-
workspaceForChat:
|
|
240
|
+
workspaceForChat: workspaceByChat.resolve,
|
|
228
241
|
})
|
|
229
242
|
const membership = createGithubMembershipResolver({ token: authToken, fetchImpl })
|
|
230
243
|
const reviewThreadResolver = createGithubReviewThreadResolver({
|
|
@@ -285,7 +298,7 @@ export function createGithubAdapter(options: GithubAdapterOptions): GithubAdapte
|
|
|
285
298
|
const pending = message.githubPendingReview
|
|
286
299
|
const prNumber = /^pr:(\d+)$/.exec(message.chat)?.[1]
|
|
287
300
|
// The webhook handler schedules this outside its acknowledgment path.
|
|
288
|
-
|
|
301
|
+
const receipt = await options.router.route(
|
|
289
302
|
{
|
|
290
303
|
...message,
|
|
291
304
|
accountIdentity: message.accountIdentity ?? (selfId === null ? undefined : `github:${selfId}`),
|
|
@@ -305,6 +318,11 @@ export function createGithubAdapter(options: GithubAdapterOptions): GithubAdapte
|
|
|
305
318
|
})
|
|
306
319
|
: undefined,
|
|
307
320
|
)
|
|
321
|
+
// Only newly accepted work runs in this process. The router also invokes the admission
|
|
322
|
+
// callback for an open duplicate, such as a redelivered trigger from a process that died.
|
|
323
|
+
if (receipt.kind === 'accepted' && pending !== undefined && prNumber !== undefined)
|
|
324
|
+
pendingAdmissions.add(pendingAdmissionKey(message.workspace, Number(prNumber), pending))
|
|
325
|
+
return receipt
|
|
308
326
|
}
|
|
309
327
|
const handlerOptions: GithubWebhookHandlerOptions = {
|
|
310
328
|
webhookSecret,
|
|
@@ -469,6 +487,7 @@ export function createGithubAdapter(options: GithubAdapterOptions): GithubAdapte
|
|
|
469
487
|
() => selfLogin,
|
|
470
488
|
)
|
|
471
489
|
}
|
|
490
|
+
unregisterSelfBridge = options.githubTokenBridge?.registerSelf(self) ?? null
|
|
472
491
|
logger.info(`[github] webhook listening on port ${options.configRef().webhookPort} as @${self.login}`)
|
|
473
492
|
// Attach before any webhook can start a review, and close checks a
|
|
474
493
|
// previous process left in progress.
|
|
@@ -604,6 +623,7 @@ export function createGithubAdapter(options: GithubAdapterOptions): GithubAdapte
|
|
|
604
623
|
fetchImpl,
|
|
605
624
|
pendingStore: loadedPendingReviewStore,
|
|
606
625
|
replayId,
|
|
626
|
+
admittedThisProcess: (entry) => pendingAdmissions.has(pendingAdmissionKey(entry.repo, entry.prNumber, entry)),
|
|
607
627
|
isCancelled: () => reconcileGeneration !== lifecycleGeneration,
|
|
608
628
|
})
|
|
609
629
|
.catch((error: unknown) => {
|
|
@@ -709,6 +729,8 @@ export function createGithubAdapter(options: GithubAdapterOptions): GithubAdapte
|
|
|
709
729
|
unregisterTokenBridge()
|
|
710
730
|
unregisterTokenBridge = null
|
|
711
731
|
}
|
|
732
|
+
unregisterSelfBridge?.()
|
|
733
|
+
unregisterSelfBridge = null
|
|
712
734
|
await auth.dispose()
|
|
713
735
|
if (options.secrets.auth.type === 'pat') delete process.env.GH_TOKEN
|
|
714
736
|
server = null
|
|
@@ -102,7 +102,12 @@ const submittedReviewsSchema = z.array(
|
|
|
102
102
|
// This path deliberately does not consult the scan age or launch cooldown. Each
|
|
103
103
|
// boot needs a fresh identity: the previous admission may be the interrupted one.
|
|
104
104
|
export async function replayPendingReviews(
|
|
105
|
-
options: ReconcileOpenPrsOptions & {
|
|
105
|
+
options: ReconcileOpenPrsOptions & {
|
|
106
|
+
pendingStore: PendingReviewStore
|
|
107
|
+
replayId: string
|
|
108
|
+
// Work this process already admitted is still live in the router; only lost work replays.
|
|
109
|
+
admittedThisProcess?: (entry: PendingReview) => boolean
|
|
110
|
+
},
|
|
106
111
|
): Promise<void> {
|
|
107
112
|
if (options.reviewOn === 'off' || options.selfLogin === null) return
|
|
108
113
|
const repos = new Set(options.repos.map(canonicalGithubRepo))
|
|
@@ -110,6 +115,7 @@ export async function replayPendingReviews(
|
|
|
110
115
|
for (const entry of await options.pendingStore.list()) {
|
|
111
116
|
if (options.isCancelled?.() === true) return
|
|
112
117
|
if (!repos.has(canonicalGithubRepo(entry.repo))) continue
|
|
118
|
+
if (options.admittedThisProcess?.(entry) === true) continue
|
|
113
119
|
try {
|
|
114
120
|
const target = parseRepo(entry.repo)
|
|
115
121
|
if (target === null) continue
|
|
@@ -8,7 +8,7 @@ export type KakaoAuthorResolver = {
|
|
|
8
8
|
}
|
|
9
9
|
|
|
10
10
|
export type KakaoAuthorResolverOptions = {
|
|
11
|
-
client: Pick<KakaoTalkClient, '
|
|
11
|
+
client: Pick<KakaoTalkClient, 'getMemberSnapshot'>
|
|
12
12
|
now?: () => number
|
|
13
13
|
ttlMs?: number
|
|
14
14
|
logger?: { warn: (msg: string) => void }
|
|
@@ -40,10 +40,12 @@ export function createKakaoAuthorResolver(options: KakaoAuthorResolverOptions):
|
|
|
40
40
|
const existing = inflight.get(chatId)
|
|
41
41
|
if (existing !== undefined) return existing
|
|
42
42
|
const promise = options.client
|
|
43
|
-
.
|
|
44
|
-
.then((
|
|
43
|
+
.getMemberSnapshot(chatId, { allowPartial: true })
|
|
44
|
+
.then((snapshot): ChatCacheEntry => {
|
|
45
|
+
// A partial roster still names most authors; misses fall back to the
|
|
46
|
+
// raw user_id exactly as a failed read does.
|
|
45
47
|
const map = new Map<string, string>()
|
|
46
|
-
for (const m of members) map.set(m.user_id, m.nickname)
|
|
48
|
+
for (const m of snapshot.members) map.set(m.user_id, m.nickname)
|
|
47
49
|
const entry: ChatCacheEntry = { members: map, expiresAt: now() + ttlMs }
|
|
48
50
|
cache.set(chatId, entry)
|
|
49
51
|
return entry
|
|
@@ -51,7 +53,7 @@ export function createKakaoAuthorResolver(options: KakaoAuthorResolverOptions):
|
|
|
51
53
|
.catch((err: unknown): null => {
|
|
52
54
|
// Author resolution is best-effort. Failing here makes the message
|
|
53
55
|
// render with the raw user_id, which is uglier but still routes.
|
|
54
|
-
logger?.warn(`[kakaotalk]
|
|
56
|
+
logger?.warn(`[kakaotalk] getMemberSnapshot(${chatId}) failed: ${describeError(err)}`)
|
|
55
57
|
return null
|
|
56
58
|
})
|
|
57
59
|
.finally(() => {
|
|
@@ -1,16 +1,16 @@
|
|
|
1
|
-
import {
|
|
2
|
-
classifyKakaoChat,
|
|
3
|
-
type KakaoChat,
|
|
4
|
-
type KakaoChatKind,
|
|
5
|
-
type KakaoMember,
|
|
6
|
-
type KakaoTalkClient,
|
|
7
|
-
} from 'agent-messenger/kakaotalk'
|
|
1
|
+
import { classifyKakaoChat, type KakaoChat, type KakaoChatKind, type KakaoMember } from 'agent-messenger/kakaotalk'
|
|
8
2
|
|
|
9
3
|
import type { ChannelKey, ChannelNameResolver, ResolvedChannelNames } from '@/channels/types'
|
|
10
4
|
|
|
11
5
|
import { describeError } from '../describe-error'
|
|
6
|
+
import type { KakaoTalkClient } from './kakaotalk'
|
|
12
7
|
|
|
13
|
-
|
|
8
|
+
// Chat names and kinds rarely change, and membership pushes trigger a refresh
|
|
9
|
+
// anyway, so a long TTL costs little. Every refresh is a full LCHATLIST walk,
|
|
10
|
+
// and the floor stops failed or unknown-chat lookups from re-walking the chat
|
|
11
|
+
// list on every message.
|
|
12
|
+
const DEFAULT_TTL_MS = 30 * 60 * 1000
|
|
13
|
+
const DEFAULT_MIN_REFRESH_INTERVAL_MS = 60 * 1000
|
|
14
14
|
|
|
15
15
|
export type KakaoWorkspace = '@kakao-dm' | '@kakao-group' | '@kakao-open'
|
|
16
16
|
|
|
@@ -35,10 +35,9 @@ export type KakaoChatLookupValue = {
|
|
|
35
35
|
|
|
36
36
|
// What a member roster PROVES about a chat — never what it merely suggests.
|
|
37
37
|
//
|
|
38
|
-
// A roster read is only ever a SUBSET of the true membership:
|
|
39
|
-
//
|
|
40
|
-
//
|
|
41
|
-
// survive adding unseen members are sound:
|
|
38
|
+
// A roster read is only ever a SUBSET of the true membership: it is read with
|
|
39
|
+
// `allowPartial`, and GETMEM can return fewer records than the room has active
|
|
40
|
+
// members. So only conclusions that survive adding unseen members are sound:
|
|
42
41
|
//
|
|
43
42
|
// - an open marker present proves OpenChat — a subset cannot invent one
|
|
44
43
|
// (`open_token` / `open_profile_link_id` / `open_permission` are
|
|
@@ -84,9 +83,11 @@ export type KakaoChannelResolver = {
|
|
|
84
83
|
}
|
|
85
84
|
|
|
86
85
|
export type KakaoChannelResolverOptions = {
|
|
87
|
-
client: Pick<KakaoTalkClient, 'getChats' | '
|
|
86
|
+
client: Pick<KakaoTalkClient, 'getChats' | 'getMemberSnapshot'>
|
|
88
87
|
now?: () => number
|
|
89
88
|
ttlMs?: number
|
|
89
|
+
minRefreshIntervalMs?: number
|
|
90
|
+
scheduleRefresh?: (fn: () => void, delayMs: number) => void
|
|
90
91
|
logger?: { warn: (msg: string) => void }
|
|
91
92
|
selfUserId?: () => string | null
|
|
92
93
|
}
|
|
@@ -102,14 +103,43 @@ type Entry = {
|
|
|
102
103
|
export function createKakaoChannelResolver(options: KakaoChannelResolverOptions): KakaoChannelResolver {
|
|
103
104
|
const now = options.now ?? Date.now
|
|
104
105
|
const ttlMs = options.ttlMs ?? DEFAULT_TTL_MS
|
|
106
|
+
const minRefreshIntervalMs = options.minRefreshIntervalMs ?? DEFAULT_MIN_REFRESH_INTERVAL_MS
|
|
105
107
|
const cache = new Map<string, Entry>()
|
|
106
108
|
let inflight: Promise<void> | null = null
|
|
109
|
+
let lastRefreshAt: number | null = null
|
|
110
|
+
let trailingScheduled = false
|
|
111
|
+
const scheduleRefresh =
|
|
112
|
+
options.scheduleRefresh ??
|
|
113
|
+
((fn: () => void, delayMs: number): void => {
|
|
114
|
+
setTimeout(fn, delayMs).unref?.()
|
|
115
|
+
})
|
|
116
|
+
|
|
117
|
+
// A suppressed refresh still owes one: a chat first seen inside the floor
|
|
118
|
+
// (a new DM) is filed provisionally under the strict group bucket, and only a
|
|
119
|
+
// real chat-list walk can upgrade it. Coalesce every suppressed request into
|
|
120
|
+
// one trailing refresh when the floor expires.
|
|
121
|
+
const scheduleTrailingRefresh = (waitMs: number): void => {
|
|
122
|
+
if (trailingScheduled) return
|
|
123
|
+
trailingScheduled = true
|
|
124
|
+
scheduleRefresh(() => {
|
|
125
|
+
trailingScheduled = false
|
|
126
|
+
void refresh()
|
|
127
|
+
}, waitMs)
|
|
128
|
+
}
|
|
107
129
|
|
|
108
130
|
const refresh = async (): Promise<void> => {
|
|
109
131
|
if (inflight !== null) {
|
|
110
132
|
await inflight
|
|
111
133
|
return
|
|
112
134
|
}
|
|
135
|
+
if (lastRefreshAt !== null) {
|
|
136
|
+
const waitMs = lastRefreshAt + minRefreshIntervalMs - now()
|
|
137
|
+
if (waitMs > 0) {
|
|
138
|
+
scheduleTrailingRefresh(waitMs)
|
|
139
|
+
return
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
lastRefreshAt = now()
|
|
113
143
|
const promise = loadAll().finally(() => {
|
|
114
144
|
inflight = null
|
|
115
145
|
})
|
|
@@ -167,8 +197,8 @@ export function createKakaoChannelResolver(options: KakaoChannelResolverOptions)
|
|
|
167
197
|
|
|
168
198
|
const provenKindFor = async (chatId: string): Promise<'open' | 'group' | null> => {
|
|
169
199
|
try {
|
|
170
|
-
const
|
|
171
|
-
return provenKindFromMembers(members, options.selfUserId?.() ?? null)
|
|
200
|
+
const snapshot = await options.client.getMemberSnapshot(chatId, { allowPartial: true })
|
|
201
|
+
return provenKindFromMembers(snapshot.members, options.selfUserId?.() ?? null)
|
|
172
202
|
} catch (err) {
|
|
173
203
|
options.logger?.warn(`[kakaotalk] provisional member lookup failed chat=${chatId}: ${describeError(err)}`)
|
|
174
204
|
return null
|
|
@@ -59,13 +59,11 @@ export function classifyInbound(
|
|
|
59
59
|
return { kind: 'drop', reason: 'unknown_chat' }
|
|
60
60
|
}
|
|
61
61
|
|
|
62
|
-
//
|
|
63
|
-
//
|
|
64
|
-
//
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
// explicit triggers). Without aliases configured, only `reply` and `dm`
|
|
68
|
-
// triggers can fire on KakaoTalk.
|
|
62
|
+
// A native @-tag carries the tagged user ids in `mentions`. Alias matching
|
|
63
|
+
// stays alongside it because people also address the bot by name without
|
|
64
|
+
// tagging, which the engagement layer treats as equivalent to a mention.
|
|
65
|
+
const mentionedUserIds = (event.mentions ?? []).map((m) => m.user_id)
|
|
66
|
+
const botTagged = mentionedUserIds.includes(context.selfUserId)
|
|
69
67
|
const aliasMatched = matchesAnyAlias(rawText, context.selfAliases ?? [])
|
|
70
68
|
|
|
71
69
|
return {
|
|
@@ -84,9 +82,9 @@ export function classifyInbound(
|
|
|
84
82
|
authorId: String(event.author_id),
|
|
85
83
|
authorName: event.author_name ?? String(event.author_id),
|
|
86
84
|
authorIsBot: false,
|
|
87
|
-
isBotMention: aliasMatched,
|
|
85
|
+
isBotMention: botTagged || aliasMatched,
|
|
88
86
|
replyToBotMessageId: replyContext?.target === 'bot' ? replyContext.logId : null,
|
|
89
|
-
mentionsOthers:
|
|
87
|
+
mentionsOthers: mentionedUserIds.length > 0 && !botTagged,
|
|
90
88
|
replyToOtherMessageId: replyContext?.target === 'other' ? replyContext.logId : null,
|
|
91
89
|
isDm: chatInfo.isDm,
|
|
92
90
|
// SDK delivers `sent_at` in Unix seconds (LOCO `sendAt`); contract
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { classifyKakaoChat, type KakaoChat } from 'agent-messenger/kakaotalk'
|
|
2
|
+
|
|
3
|
+
import type { ChannelListEntry, ListCallback, ListChannelsArgs, ListChannelsResult } from '@/channels/types'
|
|
4
|
+
|
|
5
|
+
import { describeError } from '../describe-error'
|
|
6
|
+
import type { KakaoTalkClient } from './kakaotalk'
|
|
7
|
+
import { kakaoWorkspaceForType, type KakaoWorkspace } from './kakaotalk-channel-resolver'
|
|
8
|
+
|
|
9
|
+
const KAKAO_WORKSPACES: readonly KakaoWorkspace[] = ['@kakao-dm', '@kakao-group', '@kakao-open']
|
|
10
|
+
|
|
11
|
+
// KakaoTalk has no server-side workspace: typeclaw buckets every chat into one
|
|
12
|
+
// of three synthetic workspaces by chat kind, and a later channel_send must
|
|
13
|
+
// name the same bucket. So the list is scoped to one bucket — returning every
|
|
14
|
+
// chat under an arbitrary workspace would hand back chat ids the agent cannot
|
|
15
|
+
// address. getChats has no paging, so the cursor is an offset into its result.
|
|
16
|
+
export function createKakaoListCallback(deps: {
|
|
17
|
+
client: Pick<KakaoTalkClient, 'getChats'>
|
|
18
|
+
logger: { warn: (msg: string) => void }
|
|
19
|
+
}): ListCallback {
|
|
20
|
+
return async (args: ListChannelsArgs): Promise<ListChannelsResult> => {
|
|
21
|
+
if (!isKakaoWorkspace(args.workspace)) {
|
|
22
|
+
return {
|
|
23
|
+
ok: false,
|
|
24
|
+
error: `unknown kakaotalk workspace "${args.workspace}"; use one of ${KAKAO_WORKSPACES.join(', ')}`,
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
let chats: KakaoChat[]
|
|
28
|
+
try {
|
|
29
|
+
// Without resolveTitles the SDK leaves `title` null, and a named room
|
|
30
|
+
// would only show its member names, so the agent couldn't find it by name.
|
|
31
|
+
chats = await deps.client.getChats({ all: true, resolveTitles: true })
|
|
32
|
+
} catch (err) {
|
|
33
|
+
const message = describeError(err)
|
|
34
|
+
deps.logger.warn(`[kakaotalk] chat list failed: ${message}`)
|
|
35
|
+
return { ok: false, error: message }
|
|
36
|
+
}
|
|
37
|
+
const inWorkspace = chats.filter((c) => kakaoWorkspaceForType(classifyKakaoChat(c)) === args.workspace)
|
|
38
|
+
const offset = parseOffset(args.cursor)
|
|
39
|
+
const end = offset + Math.max(1, args.limit)
|
|
40
|
+
const entries = inWorkspace.slice(offset, end).map(toListEntry)
|
|
41
|
+
return end < inWorkspace.length ? { ok: true, entries, nextCursor: String(end) } : { ok: true, entries }
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function isKakaoWorkspace(workspace: string): workspace is KakaoWorkspace {
|
|
46
|
+
return (KAKAO_WORKSPACES as readonly string[]).includes(workspace)
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function parseOffset(cursor: string | undefined): number {
|
|
50
|
+
const n = cursor === undefined ? 0 : Number.parseInt(cursor, 10)
|
|
51
|
+
return Number.isFinite(n) && n > 0 ? n : 0
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function toListEntry(chat: KakaoChat): ChannelListEntry {
|
|
55
|
+
const kind = classifyKakaoChat(chat)
|
|
56
|
+
return {
|
|
57
|
+
chat: chat.chat_id,
|
|
58
|
+
name: chat.title ?? chat.display_name ?? chat.chat_id,
|
|
59
|
+
kind: kind === 'dm' ? 'dm' : 'group',
|
|
60
|
+
isMember: true,
|
|
61
|
+
}
|
|
62
|
+
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import type { KakaoMemberSnapshot, KakaoPartialMemberSnapshot } from 'agent-messenger/kakaotalk'
|
|
2
|
+
|
|
3
|
+
import type { KakaoTalkClient } from './kakaotalk'
|
|
4
|
+
|
|
5
|
+
const DEFAULT_TTL_MS = 5 * 60 * 1000
|
|
6
|
+
const DEFAULT_FAILURE_TTL_MS = 60 * 1000
|
|
7
|
+
|
|
8
|
+
type Snapshot = KakaoMemberSnapshot | KakaoPartialMemberSnapshot
|
|
9
|
+
|
|
10
|
+
export type KakaoRosterRead = { snapshot: Snapshot; fetchedAt: number }
|
|
11
|
+
|
|
12
|
+
type Entry = { result: Promise<KakaoRosterRead>; expiresAt: number }
|
|
13
|
+
|
|
14
|
+
export type KakaoMemberSnapshotCache = Pick<KakaoTalkClient, 'getMemberSnapshot'> & {
|
|
15
|
+
// `fetchedAt` is when the server answered, never when the cache served it:
|
|
16
|
+
// freshness checks (grant_role's one-minute membership proof) must not be
|
|
17
|
+
// satisfied by an old roster replayed from cache.
|
|
18
|
+
readMemberSnapshot: (chatId: string) => Promise<KakaoRosterRead>
|
|
19
|
+
invalidate: (chatId: string) => void
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
// One GETMEM per chat per TTL, shared by every roster consumer (author names,
|
|
23
|
+
// membership counts, mention tags, provisional chat kinds). Each consumer used
|
|
24
|
+
// to read the roster on its own, so one inbound message in a group could fire
|
|
25
|
+
// several GETMEMs, and a failing read was retried on every message. KakaoTalk
|
|
26
|
+
// is a personal account: request volume like that reads as automation and
|
|
27
|
+
// risks an account restriction. Failures are cached for a shorter window so a
|
|
28
|
+
// transient error heals without hammering the server.
|
|
29
|
+
export function createKakaoMemberSnapshotCache(options: {
|
|
30
|
+
client: Pick<KakaoTalkClient, 'getMemberSnapshot'>
|
|
31
|
+
now?: () => number
|
|
32
|
+
ttlMs?: number
|
|
33
|
+
failureTtlMs?: number
|
|
34
|
+
}): KakaoMemberSnapshotCache {
|
|
35
|
+
const now = options.now ?? Date.now
|
|
36
|
+
const ttlMs = options.ttlMs ?? DEFAULT_TTL_MS
|
|
37
|
+
const failureTtlMs = options.failureTtlMs ?? DEFAULT_FAILURE_TTL_MS
|
|
38
|
+
const cache = new Map<string, Entry>()
|
|
39
|
+
|
|
40
|
+
// Keyed by chat alone: every caller reads with `allowPartial: true`.
|
|
41
|
+
const read = (chatId: string, readOptions: { allowPartial: true }): Promise<KakaoRosterRead> => {
|
|
42
|
+
const cached = cache.get(chatId)
|
|
43
|
+
if (cached !== undefined && cached.expiresAt > now()) return cached.result
|
|
44
|
+
const entry: Entry = { result: Promise.resolve(null as never), expiresAt: Number.POSITIVE_INFINITY }
|
|
45
|
+
entry.result = options.client.getMemberSnapshot(chatId, readOptions).then(
|
|
46
|
+
(snapshot) => {
|
|
47
|
+
const fetchedAt = now()
|
|
48
|
+
entry.expiresAt = fetchedAt + ttlMs
|
|
49
|
+
return { snapshot, fetchedAt }
|
|
50
|
+
},
|
|
51
|
+
(err: unknown) => {
|
|
52
|
+
entry.expiresAt = now() + failureTtlMs
|
|
53
|
+
throw err
|
|
54
|
+
},
|
|
55
|
+
)
|
|
56
|
+
cache.set(chatId, entry)
|
|
57
|
+
return entry.result
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
return {
|
|
61
|
+
getMemberSnapshot: async (chatId, readOptions) => (await read(chatId, readOptions)).snapshot,
|
|
62
|
+
readMemberSnapshot: (chatId) => read(chatId, { allowPartial: true }),
|
|
63
|
+
invalidate: (chatId) => {
|
|
64
|
+
cache.delete(chatId)
|
|
65
|
+
},
|
|
66
|
+
}
|
|
67
|
+
}
|