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
|
@@ -6,10 +6,11 @@ import type {
|
|
|
6
6
|
MembershipResolverResult,
|
|
7
7
|
} from '../membership'
|
|
8
8
|
import type { KakaoTalkClient } from './kakaotalk'
|
|
9
|
+
import type { KakaoMemberSnapshotCache } from './kakaotalk-member-cache'
|
|
9
10
|
|
|
10
11
|
export type KakaoMembershipResolverOptions = {
|
|
11
|
-
client: Pick<KakaoTalkClient, '
|
|
12
|
-
// The logged-in agent's own KakaoTalk user_id. Returned
|
|
12
|
+
client: Pick<KakaoTalkClient, 'getMemberSnapshot'>
|
|
13
|
+
// The logged-in agent's own KakaoTalk user_id. Returned in the roster
|
|
13
14
|
// alongside every human in the room, so it must be excluded from the
|
|
14
15
|
// human count — otherwise a 1:1 chat (agent + one human) reports two
|
|
15
16
|
// humans and a real group is off by one. Null before login completes,
|
|
@@ -17,6 +18,9 @@ export type KakaoMembershipResolverOptions = {
|
|
|
17
18
|
selfUserIdRef: () => string | null
|
|
18
19
|
logger: { warn: (msg: string) => void }
|
|
19
20
|
now?: () => number
|
|
21
|
+
// Cached roster reads carry the time the server answered, which becomes
|
|
22
|
+
// `fetchedAt`. Without it, a direct client read is stamped `now()`.
|
|
23
|
+
roster?: Pick<KakaoMemberSnapshotCache, 'readMemberSnapshot'>
|
|
20
24
|
}
|
|
21
25
|
|
|
22
26
|
// Without a registered resolver the router's `resolveEffectiveHumans` falls
|
|
@@ -24,9 +28,13 @@ export type KakaoMembershipResolverOptions = {
|
|
|
24
28
|
// session. On a cold-started group that is just the sender, tripping the
|
|
25
29
|
// engagement layer's solo-human "answer everything" fallback so the agent
|
|
26
30
|
// replies to messages aimed at others. Every other adapter registers a
|
|
27
|
-
// resolver; KakaoTalk was the lone gap.
|
|
28
|
-
//
|
|
29
|
-
//
|
|
31
|
+
// resolver; KakaoTalk was the lone gap. The roster is read with `allowPartial`:
|
|
32
|
+
// GETMEM can return fewer records than the room's active member count (large
|
|
33
|
+
// open chats), where the strict read throws on every call. A complete snapshot
|
|
34
|
+
// is reported as non-truncated with its member ids; a partial one is reported
|
|
35
|
+
// as truncated without ids, counting humans from the room's active member count, so consumers that need a completeness proof fail
|
|
36
|
+
// closed. We never opt into `allowRoomEntry`, because CHATONROOM can advance
|
|
37
|
+
// the account's unread state.
|
|
30
38
|
// Room rosters list only human accounts plus the agent's own; hence
|
|
31
39
|
// `humans = roster excluding self` and `bots: 1` (the agent) — `bots: 0` would
|
|
32
40
|
// defeat the engagement layer's peer-bot loop suppression.
|
|
@@ -42,17 +50,26 @@ export function createKakaoMembershipResolver(options: KakaoMembershipResolverOp
|
|
|
42
50
|
return { kind: 'transient' } satisfies MembershipResolverFailure
|
|
43
51
|
}
|
|
44
52
|
try {
|
|
45
|
-
const
|
|
46
|
-
|
|
47
|
-
|
|
53
|
+
const { snapshot, fetchedAt } =
|
|
54
|
+
options.roster !== undefined
|
|
55
|
+
? await options.roster.readMemberSnapshot(key.chat)
|
|
56
|
+
: { snapshot: await options.client.getMemberSnapshot(key.chat, { allowPartial: true }), fetchedAt: now() }
|
|
57
|
+
// Dedupe by user_id defensively; a roster should not repeat a member.
|
|
48
58
|
const memberIds = new Set<string>()
|
|
49
|
-
for (const m of members) memberIds.add(m.user_id)
|
|
59
|
+
for (const m of snapshot.members) memberIds.add(m.user_id)
|
|
50
60
|
memberIds.delete(selfUserId)
|
|
51
61
|
const humanMemberIds = [...memberIds]
|
|
62
|
+
if (!snapshot.complete) {
|
|
63
|
+
// The returned records can be a tiny slice of a large room. The
|
|
64
|
+
// server's active count (which includes the agent) keeps the
|
|
65
|
+
// approximate total from collapsing to the solo-human fallback.
|
|
66
|
+
const humans = Math.max(humanMemberIds.length, snapshot.active_members - 1)
|
|
67
|
+
return { humans, bots: 1, fetchedAt, truncated: true } satisfies MembershipCount
|
|
68
|
+
}
|
|
52
69
|
return {
|
|
53
70
|
humans: humanMemberIds.length,
|
|
54
71
|
bots: 1,
|
|
55
|
-
fetchedAt
|
|
72
|
+
fetchedAt,
|
|
56
73
|
truncated: false,
|
|
57
74
|
humanMemberIds,
|
|
58
75
|
} satisfies MembershipCount
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import type { KakaoMember, KakaoMentionInput } from 'agent-messenger/kakaotalk'
|
|
2
|
+
|
|
3
|
+
const WORD_CONTINUATION = /[\p{Script=Latin}\p{N}_]/u
|
|
4
|
+
|
|
5
|
+
// Turns `@<nickname>` tags the agent wrote into native KakaoTalk mentions for
|
|
6
|
+
// the chat's members. The SDK's `buildMentions` gives each `@` to the longest
|
|
7
|
+
// REQUESTED name that matches there and throws when a requested name wins no
|
|
8
|
+
// `@`. So a target is requested only when it wins an `@` among every member
|
|
9
|
+
// name, and a nickname two members share is never requested (its tag cannot
|
|
10
|
+
// pick one). Because the SDK only sees requested names, a shorter target could
|
|
11
|
+
// still claim an `@` whose real winner was such an ambiguous name; any target
|
|
12
|
+
// that would is dropped too, leaving that text untagged rather than mis-tagged.
|
|
13
|
+
export function resolveKakaoMentions(text: string, members: readonly KakaoMember[]): KakaoMentionInput[] {
|
|
14
|
+
if (!text.includes('@')) return []
|
|
15
|
+
const idByName = new Map<string, string | null>()
|
|
16
|
+
for (const m of members) {
|
|
17
|
+
if (m.nickname === '') continue
|
|
18
|
+
idByName.set(m.nickname, idByName.has(m.nickname) ? null : m.user_id)
|
|
19
|
+
}
|
|
20
|
+
const allNames = [...idByName.keys()]
|
|
21
|
+
const intendedWinners = atPositions(text).map((i) => longestTagAt(text, i, allNames))
|
|
22
|
+
const requested = new Set(intendedWinners.filter((n): n is string => n !== undefined && idByName.get(n) !== null))
|
|
23
|
+
|
|
24
|
+
for (let changed = true; changed; ) {
|
|
25
|
+
changed = false
|
|
26
|
+
atPositions(text).forEach((i, k) => {
|
|
27
|
+
const sdkWinner = longestTagAt(text, i, [...requested])
|
|
28
|
+
if (sdkWinner !== undefined && sdkWinner !== intendedWinners[k]) {
|
|
29
|
+
requested.delete(sdkWinner)
|
|
30
|
+
changed = true
|
|
31
|
+
}
|
|
32
|
+
})
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
return [...requested].map((name) => ({ user_id: idByName.get(name)!, name }))
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function atPositions(text: string): number[] {
|
|
39
|
+
const positions: number[] = []
|
|
40
|
+
for (let i = text.indexOf('@'); i !== -1; i = text.indexOf('@', i + 1)) positions.push(i)
|
|
41
|
+
return positions
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function longestTagAt(text: string, at: number, names: readonly string[]): string | undefined {
|
|
45
|
+
let best: string | undefined
|
|
46
|
+
for (const n of names) {
|
|
47
|
+
if (best !== undefined && n.length <= best.length) continue
|
|
48
|
+
if (text.startsWith(n, at + 1) && endsTag(text, at + 1 + n.length, n)) best = n
|
|
49
|
+
}
|
|
50
|
+
return best
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// A Latin/digit-final name followed by another Latin/digit is a longer word,
|
|
54
|
+
// not a tag. Anything else may follow, since Korean particles attach directly
|
|
55
|
+
// to a name (`@연규님`).
|
|
56
|
+
function endsTag(text: string, end: number, name: string): boolean {
|
|
57
|
+
const next = text[end]
|
|
58
|
+
if (next === undefined) return true
|
|
59
|
+
const last = [...name].at(-1) ?? ''
|
|
60
|
+
return !(WORD_CONTINUATION.test(last) && WORD_CONTINUATION.test(next))
|
|
61
|
+
}
|
|
@@ -7,8 +7,9 @@ import {
|
|
|
7
7
|
type AttachmentInput,
|
|
8
8
|
type KakaoChat,
|
|
9
9
|
type KakaoMarkReadResult,
|
|
10
|
-
type
|
|
10
|
+
type KakaoMemberSnapshot,
|
|
11
11
|
type KakaoMessage,
|
|
12
|
+
type KakaoPartialMemberSnapshot,
|
|
12
13
|
type KakaoProfile,
|
|
13
14
|
type KakaoReplyTarget,
|
|
14
15
|
type KakaoSendResult,
|
|
@@ -17,7 +18,12 @@ import {
|
|
|
17
18
|
type KakaoTalkPushMessageEvent,
|
|
18
19
|
type KakaoTypingResult,
|
|
19
20
|
} from 'agent-messenger/kakaotalk'
|
|
20
|
-
import type {
|
|
21
|
+
import type {
|
|
22
|
+
KakaoAccountCredentials,
|
|
23
|
+
KakaoConfig,
|
|
24
|
+
KakaoMentionInput,
|
|
25
|
+
PendingLoginState,
|
|
26
|
+
} from 'agent-messenger/kakaotalk'
|
|
21
27
|
|
|
22
28
|
import { prependQuoteAnchor, type ChannelRouter } from '@/channels/router'
|
|
23
29
|
import type { ChannelAdapterConfig } from '@/channels/schema'
|
|
@@ -35,6 +41,7 @@ import type {
|
|
|
35
41
|
InboundAttachment,
|
|
36
42
|
} from '@/channels/types'
|
|
37
43
|
|
|
44
|
+
import { ChannelAdapterHaltedError } from '../adapter-halt'
|
|
38
45
|
import { describeError } from '../describe-error'
|
|
39
46
|
import {
|
|
40
47
|
emoticonEventToMessageEvent,
|
|
@@ -47,7 +54,10 @@ import { createKakaoChannelResolver, type KakaoChannelResolver } from './kakaota
|
|
|
47
54
|
import { classifyInbound, type InboundDropReason } from './kakaotalk-classify'
|
|
48
55
|
import { createFetchAttachmentCallback } from './kakaotalk-fetch-attachment'
|
|
49
56
|
import { toKakaoPlainText } from './kakaotalk-format'
|
|
57
|
+
import { createKakaoListCallback } from './kakaotalk-list'
|
|
58
|
+
import { createKakaoMemberSnapshotCache } from './kakaotalk-member-cache'
|
|
50
59
|
import { createKakaoMembershipResolver } from './kakaotalk-membership'
|
|
60
|
+
import { resolveKakaoMentions } from './kakaotalk-mention'
|
|
51
61
|
import { createKakaoTypingCallback, kakaoTypingClassFromLookup, KAKAO_TYPING_HEARTBEAT_MS } from './kakaotalk-typing'
|
|
52
62
|
import { withOutboundAccount } from './outbound-account'
|
|
53
63
|
|
|
@@ -62,9 +72,13 @@ export interface KakaoTalkClient {
|
|
|
62
72
|
credentials?: { oauthToken: string; userId: string; deviceUuid?: string; deviceType?: 'pc' | 'tablet' },
|
|
63
73
|
accountId?: string,
|
|
64
74
|
): Promise<this>
|
|
65
|
-
getChats(options?: { all?: boolean; search?: string }): Promise<KakaoChat[]>
|
|
75
|
+
getChats(options?: { all?: boolean; search?: string; resolveTitles?: boolean }): Promise<KakaoChat[]>
|
|
66
76
|
getMessages(chatId: string, options?: { count?: number; from?: string }): Promise<KakaoMessage[]>
|
|
67
|
-
sendMessage(
|
|
77
|
+
sendMessage(
|
|
78
|
+
chatId: string,
|
|
79
|
+
text: string,
|
|
80
|
+
options?: { replyTo?: KakaoReplyTarget; mentions?: KakaoMentionInput[] },
|
|
81
|
+
): Promise<KakaoSendResult>
|
|
68
82
|
sendAttachment(
|
|
69
83
|
chatId: string,
|
|
70
84
|
data: Uint8Array | Buffer,
|
|
@@ -75,7 +89,13 @@ export interface KakaoTalkClient {
|
|
|
75
89
|
markRead(chatId: string, logId: string, opts?: { linkId?: string }): Promise<KakaoMarkReadResult>
|
|
76
90
|
sendTyping(chatId: string, opts?: { linkId?: string }): Promise<KakaoTypingResult>
|
|
77
91
|
getProfile(): Promise<KakaoProfile>
|
|
78
|
-
|
|
92
|
+
// Always called with `allowPartial: true`: the strict default throws on every
|
|
93
|
+
// read in open chats whose GETMEM roster is capped below the active member
|
|
94
|
+
// count, which would leave those rooms with no roster at all.
|
|
95
|
+
getMemberSnapshot(
|
|
96
|
+
chatId: string,
|
|
97
|
+
options: { allowPartial: true },
|
|
98
|
+
): Promise<KakaoMemberSnapshot | KakaoPartialMemberSnapshot>
|
|
79
99
|
lookupAuthorName(chatId: string, authorId: number): string | null
|
|
80
100
|
close(): void
|
|
81
101
|
}
|
|
@@ -132,42 +152,22 @@ export type KakaotalkAdapterOptions = {
|
|
|
132
152
|
credentialsDir?: string
|
|
133
153
|
client?: KakaoTalkClient
|
|
134
154
|
listenerFactory?: (client: KakaoTalkClient) => KakaoTalkListener
|
|
135
|
-
// Test seam for KICKOUT auto-recovery. Production uses Date.now and
|
|
136
|
-
// setTimeout. Tests inject deterministic clocks/schedulers so they can
|
|
137
|
-
// assert the recovery semantics without real-time waits.
|
|
138
|
-
now?: () => number
|
|
139
|
-
scheduleRecovery?: (fn: () => void, delayMs: number) => void
|
|
140
155
|
}
|
|
141
156
|
|
|
142
|
-
// LOCO emits KICKOUT when the
|
|
143
|
-
//
|
|
144
|
-
//
|
|
145
|
-
//
|
|
146
|
-
//
|
|
147
|
-
//
|
|
148
|
-
// ~1-2 minutes until it times out. Old one-shot recovery
|
|
149
|
-
// reconnected once, got kicked again, and died — the bug this
|
|
150
|
-
// state machine exists to fix.
|
|
151
|
-
// 3. Real conflict — another device or process holds the same
|
|
152
|
-
// device_uuid. Our retries can't win this fight; we should give up
|
|
153
|
-
// cleanly so the user notices and intervenes.
|
|
154
|
-
// One signal, three shapes: we always try to recover, but with a
|
|
155
|
-
// strictly bounded budget. Within an episode we allow KICKOUT_RECOVERY_
|
|
156
|
-
// _DELAYS_MS.length retries spaced by the listed delays; an episode is
|
|
157
|
-
// declared successful only after the reconnect stays connected for
|
|
158
|
-
// SUCCESS_MS (bare `connected` is too weak — ghost ping-pong reconnects
|
|
159
|
-
// for seconds before getting kicked again). Past the budget or the
|
|
160
|
-
// MAX_ELAPSED cap we let the session die. After a successful episode
|
|
161
|
-
// the state resets, so a fresh KICKOUT hours later gets a fresh
|
|
162
|
-
// episode rather than being permanently locked out.
|
|
163
|
-
const KICKOUT_RECOVERY_SUCCESS_MS = 60_000
|
|
164
|
-
const KICKOUT_RECOVERY_MAX_ELAPSED_MS = 5 * 60_000
|
|
165
|
-
const KICKOUT_RECOVERY_DELAYS_MS: readonly number[] = [2_000, 10_000, 60_000]
|
|
157
|
+
// LOCO emits KICKOUT when the server ends this session: another login with
|
|
158
|
+
// the same device_uuid, or KakaoTalk acting on the account itself. We never
|
|
159
|
+
// log in again on our own after one. A kick that turns out to be an account
|
|
160
|
+
// action makes every reconnect a rejected login, and repeated rejected logins
|
|
161
|
+
// can escalate a temporary KakaoTalk restriction into a permanent one. The
|
|
162
|
+
// adapter halts and waits for an operator.
|
|
166
163
|
|
|
167
164
|
export type KakaotalkAdapter = {
|
|
168
165
|
start: () => Promise<void>
|
|
169
166
|
stop: () => Promise<void>
|
|
170
167
|
isConnected: () => boolean
|
|
168
|
+
// Non-null once the adapter gave up on its session for a reason a retry with
|
|
169
|
+
// the same credentials cannot fix. The manager stops supervising restarts.
|
|
170
|
+
haltReason?: () => string | null
|
|
171
171
|
}
|
|
172
172
|
|
|
173
173
|
export const KAKAO_HISTORY_LIMIT_MAX = 200
|
|
@@ -188,12 +188,14 @@ async function readAttachmentBuffer(path: string): Promise<Buffer> {
|
|
|
188
188
|
}
|
|
189
189
|
|
|
190
190
|
export function createOutboundCallback(deps: {
|
|
191
|
-
client: Pick<KakaoTalkClient, 'sendMessage' | 'sendAttachment' | 'getMessages'>
|
|
191
|
+
client: Pick<KakaoTalkClient, 'sendMessage' | 'sendAttachment' | 'getMessages' | 'getMemberSnapshot'>
|
|
192
192
|
logger: KakaotalkAdapterLogger
|
|
193
193
|
formatChannelTag: (workspace: string, chat: string) => Promise<string>
|
|
194
194
|
readFile?: (path: string) => Promise<Buffer>
|
|
195
|
+
roster?: Pick<KakaoTalkClient, 'getMemberSnapshot'>
|
|
195
196
|
}): OutboundCallback {
|
|
196
197
|
const { client, logger, formatChannelTag } = deps
|
|
198
|
+
const roster = deps.roster ?? client
|
|
197
199
|
const readFile = deps.readFile ?? readAttachmentBuffer
|
|
198
200
|
return async (msg: OutboundMessage): Promise<SendResult> => {
|
|
199
201
|
if (msg.adapter !== 'kakaotalk') {
|
|
@@ -256,12 +258,12 @@ export function createOutboundCallback(deps: {
|
|
|
256
258
|
outboundText = prependQuoteAnchor(text, msg.replyTo.source)
|
|
257
259
|
}
|
|
258
260
|
}
|
|
261
|
+
const mentions = await resolveOutboundMentions(roster, msg.chat, outboundText, logger)
|
|
259
262
|
try {
|
|
260
|
-
const result = await client.sendMessage(
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
)
|
|
263
|
+
const result = await client.sendMessage(msg.chat, outboundText, {
|
|
264
|
+
...(replyTarget !== undefined ? { replyTo: replyTarget } : {}),
|
|
265
|
+
...(mentions.length > 0 ? { mentions } : {}),
|
|
266
|
+
})
|
|
265
267
|
if (!result.success) {
|
|
266
268
|
logger.error(`[kakaotalk] sendMessage status_code=${result.status_code} ${tag}`)
|
|
267
269
|
return { ok: false, error: `kakaotalk send failed with status ${result.status_code}` }
|
|
@@ -283,6 +285,30 @@ export function createOutboundCallback(deps: {
|
|
|
283
285
|
}
|
|
284
286
|
}
|
|
285
287
|
|
|
288
|
+
// A failed member lookup only costs the native tags: the text still carries
|
|
289
|
+
// the `@name` the agent wrote, so the send goes out untagged.
|
|
290
|
+
async function resolveOutboundMentions(
|
|
291
|
+
client: Pick<KakaoTalkClient, 'getMemberSnapshot'>,
|
|
292
|
+
chatId: string,
|
|
293
|
+
text: string,
|
|
294
|
+
logger: KakaotalkAdapterLogger,
|
|
295
|
+
): Promise<KakaoMentionInput[]> {
|
|
296
|
+
if (!text.includes('@')) return []
|
|
297
|
+
try {
|
|
298
|
+
const snapshot = await client.getMemberSnapshot(chatId, { allowPartial: true })
|
|
299
|
+
// Nickname matching is only safe against the whole roster: an omitted
|
|
300
|
+
// duplicate or longer nickname would tag the wrong member. Send untagged.
|
|
301
|
+
if (!snapshot.complete) {
|
|
302
|
+
logger.info(`[kakaotalk] mention roster incomplete chat=${chatId}; sending untagged`)
|
|
303
|
+
return []
|
|
304
|
+
}
|
|
305
|
+
return resolveKakaoMentions(text, snapshot.members)
|
|
306
|
+
} catch (err) {
|
|
307
|
+
logger.warn(`[kakaotalk] mention member lookup failed chat=${chatId}: ${describeError(err)}`)
|
|
308
|
+
return []
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
|
|
286
312
|
// KakaoTalk replies need the full source message, not just its log_id. Resolve
|
|
287
313
|
// it from the chat's recent history (matching the upstream CLI's approach).
|
|
288
314
|
// Returns undefined when the target isn't in the fetched window or the fetch
|
|
@@ -355,37 +381,61 @@ function clampLimit(requested: number, max: number): number {
|
|
|
355
381
|
|
|
356
382
|
export function createKakaotalkAdapter(options: KakaotalkAdapterOptions): KakaotalkAdapter {
|
|
357
383
|
const logger = options.logger ?? consoleLogger
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
384
|
+
// The SDK reconnects lazily: any call on a dropped session (a typing pulse,
|
|
385
|
+
// a send, a history read) runs a fresh LOGINLIST, and its callers only log
|
|
386
|
+
// failures. Every call goes through this guard so the first rejected login
|
|
387
|
+
// halts the adapter, wherever it surfaces.
|
|
388
|
+
const client = guardLoginRejections(options.client ?? new KakaoTalkClient(), (err) => {
|
|
389
|
+
haltOnLoginRejection(err)
|
|
390
|
+
})
|
|
365
391
|
let listener: KakaoTalkListener | null = null
|
|
366
392
|
let selfUserId: string | null = null
|
|
367
393
|
const selfIdentityResolver: ChannelSelfIdentityResolver = () => (selfUserId === null ? null : { id: selfUserId })
|
|
368
394
|
let connected = false
|
|
369
395
|
let started = false
|
|
370
|
-
let lastConnectedAt: number | null = null
|
|
371
396
|
let inflightInbounds = 0
|
|
372
397
|
let stopWaiters: Array<() => void> = []
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
398
|
+
let haltReason: string | null = null
|
|
399
|
+
|
|
400
|
+
// Every SDK call on a dead session opens a new LOCO login, so a halt closes
|
|
401
|
+
// the client at once instead of waiting for the manager's next supervision
|
|
402
|
+
// tick: typing heartbeats and inbound bookkeeping would otherwise keep
|
|
403
|
+
// logging in against an account the server already refused.
|
|
404
|
+
const halt = (reason: string): void => {
|
|
405
|
+
if (haltReason !== null) return
|
|
406
|
+
haltReason = reason
|
|
407
|
+
connected = false
|
|
408
|
+
logger.error(`[kakaotalk] halted: ${reason}`)
|
|
409
|
+
listener?.stop()
|
|
410
|
+
listener = null
|
|
411
|
+
try {
|
|
412
|
+
client.close()
|
|
413
|
+
} catch {
|
|
414
|
+
// The session is unusable either way; nothing to recover here.
|
|
415
|
+
}
|
|
378
416
|
}
|
|
379
|
-
let recoveryEpisode: RecoveryEpisode | null = null
|
|
380
417
|
|
|
381
|
-
const
|
|
382
|
-
|
|
418
|
+
const haltOnLoginRejection = (err: unknown): boolean => {
|
|
419
|
+
const status = kakaoLoginRejectionStatus(err)
|
|
420
|
+
if (status === null) return false
|
|
421
|
+
halt(
|
|
422
|
+
`KakaoTalk rejected the login (LOGINLIST status ${status}). Retrying with the same session only sends more ` +
|
|
423
|
+
'rejected logins, which KakaoTalk can treat as abuse. Check the account in the KakaoTalk app, then run ' +
|
|
424
|
+
'`typeclaw channel reauth kakaotalk` or `typeclaw restart`.',
|
|
425
|
+
)
|
|
426
|
+
return true
|
|
383
427
|
}
|
|
384
428
|
|
|
385
|
-
const
|
|
386
|
-
const
|
|
429
|
+
const roster = createKakaoMemberSnapshotCache({ client })
|
|
430
|
+
const channelResolver = createKakaoChannelResolver({
|
|
431
|
+
client: { getChats: (opts) => client.getChats(opts), getMemberSnapshot: roster.getMemberSnapshot },
|
|
432
|
+
logger,
|
|
433
|
+
selfUserId: () => selfUserId,
|
|
434
|
+
})
|
|
435
|
+
const authorResolver = createKakaoAuthorResolver({ client: roster, logger })
|
|
387
436
|
const membershipResolver = createKakaoMembershipResolver({
|
|
388
|
-
client,
|
|
437
|
+
client: roster,
|
|
438
|
+
roster,
|
|
389
439
|
selfUserIdRef: () => selfUserId,
|
|
390
440
|
logger,
|
|
391
441
|
})
|
|
@@ -403,12 +453,14 @@ export function createKakaotalkAdapter(options: KakaotalkAdapterOptions): Kakaot
|
|
|
403
453
|
authorResolver,
|
|
404
454
|
selfUserIdRef: () => selfUserId,
|
|
405
455
|
})
|
|
456
|
+
const listCallback = createKakaoListCallback({ client, logger })
|
|
406
457
|
|
|
407
458
|
const outboundCallback = withOutboundAccount(
|
|
408
459
|
createOutboundCallback({
|
|
409
460
|
client,
|
|
410
461
|
logger,
|
|
411
462
|
formatChannelTag,
|
|
463
|
+
roster,
|
|
412
464
|
}),
|
|
413
465
|
(workspace) => fallbackChannelAccountIdentity('kakaotalk', workspace, selfUserId),
|
|
414
466
|
)
|
|
@@ -521,8 +573,7 @@ export function createKakaotalkAdapter(options: KakaotalkAdapterOptions): Kakaot
|
|
|
521
573
|
async start(): Promise<void> {
|
|
522
574
|
if (started) return
|
|
523
575
|
started = true
|
|
524
|
-
|
|
525
|
-
resetRecoveryEpisode()
|
|
576
|
+
haltReason = null
|
|
526
577
|
try {
|
|
527
578
|
const credentialStore =
|
|
528
579
|
options.credentialsStore ??
|
|
@@ -567,7 +618,7 @@ export function createKakaotalkAdapter(options: KakaotalkAdapterOptions): Kakaot
|
|
|
567
618
|
'either because the agent was just initialized without stored credentials, or because the encryption key ' +
|
|
568
619
|
'is missing/wrong. Run `typeclaw channel reauth kakaotalk` to mint fresh tokens, then `typeclaw reload`.'
|
|
569
620
|
logger.error(`[kakaotalk] ${message}`)
|
|
570
|
-
throw new
|
|
621
|
+
throw new ChannelAdapterHaltedError(message)
|
|
571
622
|
}
|
|
572
623
|
logger.error(`[kakaotalk] getProfile failed: ${describeError(err)}`)
|
|
573
624
|
throw err
|
|
@@ -578,30 +629,15 @@ export function createKakaotalkAdapter(options: KakaotalkAdapterOptions): Kakaot
|
|
|
578
629
|
} catch (err) {
|
|
579
630
|
logger.warn(`[kakaotalk] initial chat list fetch failed: ${describeError(err)}`)
|
|
580
631
|
}
|
|
632
|
+
if (haltReason !== null) {
|
|
633
|
+
started = false
|
|
634
|
+
throw new ChannelAdapterHaltedError(haltReason)
|
|
635
|
+
}
|
|
581
636
|
|
|
582
637
|
listener = options.listenerFactory ? options.listenerFactory(client) : new KakaoTalkListener(client)
|
|
583
|
-
const activeListener = listener
|
|
584
|
-
const scheduleStabilityCheck = (): void => {
|
|
585
|
-
if (recoveryEpisode === null) return
|
|
586
|
-
if (recoveryEpisode.pendingStabilityCheck) return
|
|
587
|
-
recoveryEpisode.pendingStabilityCheck = true
|
|
588
|
-
const expectedConnectedAt = lastConnectedAt
|
|
589
|
-
scheduleRecovery(() => {
|
|
590
|
-
if (recoveryEpisode === null) return
|
|
591
|
-
recoveryEpisode.pendingStabilityCheck = false
|
|
592
|
-
if (!started || listener !== activeListener) return
|
|
593
|
-
if (!connected || lastConnectedAt !== expectedConnectedAt) return
|
|
594
|
-
logger.info(
|
|
595
|
-
`[kakaotalk] KICKOUT recovery episode succeeded after ${recoveryEpisode.attemptCount} attempt(s); session is stable.`,
|
|
596
|
-
)
|
|
597
|
-
resetRecoveryEpisode()
|
|
598
|
-
}, KICKOUT_RECOVERY_SUCCESS_MS)
|
|
599
|
-
}
|
|
600
638
|
listener.on('connected', (info) => {
|
|
601
639
|
connected = true
|
|
602
|
-
lastConnectedAt = now()
|
|
603
640
|
logger.info(`[kakaotalk] connected (user_id=${info.userId})`)
|
|
604
|
-
if (recoveryEpisode !== null) scheduleStabilityCheck()
|
|
605
641
|
})
|
|
606
642
|
listener.on('disconnected', () => {
|
|
607
643
|
connected = false
|
|
@@ -609,48 +645,13 @@ export function createKakaotalkAdapter(options: KakaotalkAdapterOptions): Kakaot
|
|
|
609
645
|
})
|
|
610
646
|
listener.on('error', (err) => {
|
|
611
647
|
logger.error(`[kakaotalk] listener error: ${describeError(err)}`)
|
|
648
|
+
if (haltReason !== null || haltOnLoginRejection(err)) return
|
|
612
649
|
if (!isKickoutError(err)) return
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
if (!started) return
|
|
618
|
-
const tNow = now()
|
|
619
|
-
if (recoveryEpisode === null) {
|
|
620
|
-
recoveryEpisode = { startedAt: tNow, attemptCount: 0, pendingStabilityCheck: false }
|
|
621
|
-
}
|
|
622
|
-
const episode = recoveryEpisode
|
|
623
|
-
const elapsedInEpisode = tNow - episode.startedAt
|
|
624
|
-
const nextAttemptIndex = episode.attemptCount
|
|
625
|
-
const delayMs = KICKOUT_RECOVERY_DELAYS_MS[nextAttemptIndex]
|
|
626
|
-
if (delayMs === undefined || elapsedInEpisode + delayMs > KICKOUT_RECOVERY_MAX_ELAPSED_MS) {
|
|
627
|
-
const reason =
|
|
628
|
-
delayMs === undefined
|
|
629
|
-
? `${KICKOUT_RECOVERY_DELAYS_MS.length} attempt(s) exhausted`
|
|
630
|
-
: `${Math.round(KICKOUT_RECOVERY_MAX_ELAPSED_MS / 1000)}s recovery budget exhausted`
|
|
631
|
-
logger.error(
|
|
632
|
-
`[kakaotalk] session is DEAD after KICKOUT — ${reason}. ` +
|
|
633
|
-
'Likely a real cross-device login is fighting our session. ' +
|
|
634
|
-
'Stop the other client, then run `typeclaw restart`. ' +
|
|
635
|
-
'If the conflict persists, run `typeclaw channel reauth kakaotalk` to mint a fresh sub-device session ' +
|
|
636
|
-
'(the existing device_uuid is preserved by default so the new login skips phone-passcode confirmation).',
|
|
637
|
-
)
|
|
638
|
-
resetRecoveryEpisode()
|
|
639
|
-
return
|
|
640
|
-
}
|
|
641
|
-
episode.attemptCount = nextAttemptIndex + 1
|
|
642
|
-
logger.warn(
|
|
643
|
-
`[kakaotalk] KICKOUT during recovery episode (attempt ${episode.attemptCount}/${KICKOUT_RECOVERY_DELAYS_MS.length}, episode_elapsed=${Math.round(elapsedInEpisode)}ms); reconnecting in ${delayMs}ms.`,
|
|
650
|
+
halt(
|
|
651
|
+
'KakaoTalk ended this session (KICKOUT); not logging in again automatically. ' +
|
|
652
|
+
'If another client uses the same device, stop it. Check the account in the KakaoTalk app, then run ' +
|
|
653
|
+
'`typeclaw restart`, or `typeclaw channel reauth kakaotalk` for a fresh sub-device session.',
|
|
644
654
|
)
|
|
645
|
-
scheduleRecovery(() => {
|
|
646
|
-
if (!started || listener !== activeListener) return
|
|
647
|
-
if (recoveryEpisode !== episode) return
|
|
648
|
-
activeListener.start().catch((retryErr) => {
|
|
649
|
-
logger.error(
|
|
650
|
-
`[kakaotalk] KICKOUT auto-recovery failed: ${describeError(retryErr)}. Run \`typeclaw restart\` to retry.`,
|
|
651
|
-
)
|
|
652
|
-
})
|
|
653
|
-
}, delayMs)
|
|
654
655
|
})
|
|
655
656
|
listener.on('message', (event) => {
|
|
656
657
|
void handleMessageEvent(event)
|
|
@@ -658,10 +659,12 @@ export function createKakaotalkAdapter(options: KakaotalkAdapterOptions): Kakaot
|
|
|
658
659
|
listener.on('emoticon', (event) => {
|
|
659
660
|
void handleEmoticonEvent(event)
|
|
660
661
|
})
|
|
661
|
-
listener.on('member_joined', () => {
|
|
662
|
+
listener.on('member_joined', (event) => {
|
|
663
|
+
roster.invalidate(event.chat_id)
|
|
662
664
|
void channelResolver.refresh()
|
|
663
665
|
})
|
|
664
|
-
listener.on('member_left', () => {
|
|
666
|
+
listener.on('member_left', (event) => {
|
|
667
|
+
roster.invalidate(event.chat_id)
|
|
665
668
|
void channelResolver.refresh()
|
|
666
669
|
})
|
|
667
670
|
|
|
@@ -700,6 +703,7 @@ export function createKakaotalkAdapter(options: KakaotalkAdapterOptions): Kakaot
|
|
|
700
703
|
options.router.setTypingHeartbeatInterval('kakaotalk', KAKAO_TYPING_HEARTBEAT_MS)
|
|
701
704
|
options.router.registerChannelNameResolver('kakaotalk', channelResolver.resolve)
|
|
702
705
|
options.router.registerHistory('kakaotalk', historyCallback)
|
|
706
|
+
options.router.registerList('kakaotalk', listCallback)
|
|
703
707
|
options.router.registerFetchAttachment('kakaotalk', fetchAttachmentCallback)
|
|
704
708
|
options.router.registerMembership('kakaotalk', membershipResolver)
|
|
705
709
|
},
|
|
@@ -714,6 +718,7 @@ export function createKakaotalkAdapter(options: KakaotalkAdapterOptions): Kakaot
|
|
|
714
718
|
typing.reset()
|
|
715
719
|
options.router.unregisterChannelNameResolver('kakaotalk', channelResolver.resolve)
|
|
716
720
|
options.router.unregisterHistory('kakaotalk', historyCallback)
|
|
721
|
+
options.router.unregisterList('kakaotalk', listCallback)
|
|
717
722
|
options.router.unregisterFetchAttachment('kakaotalk', fetchAttachmentCallback)
|
|
718
723
|
options.router.unregisterMembership('kakaotalk', membershipResolver)
|
|
719
724
|
if (inflightInbounds > 0) {
|
|
@@ -731,13 +736,15 @@ export function createKakaotalkAdapter(options: KakaotalkAdapterOptions): Kakaot
|
|
|
731
736
|
}
|
|
732
737
|
selfUserId = null
|
|
733
738
|
connected = false
|
|
734
|
-
lastConnectedAt = null
|
|
735
|
-
resetRecoveryEpisode()
|
|
736
739
|
},
|
|
737
740
|
|
|
738
741
|
isConnected(): boolean {
|
|
739
742
|
return connected && selfUserId !== null
|
|
740
743
|
},
|
|
744
|
+
|
|
745
|
+
haltReason(): string | null {
|
|
746
|
+
return haltReason
|
|
747
|
+
},
|
|
741
748
|
}
|
|
742
749
|
}
|
|
743
750
|
|
|
@@ -786,6 +793,33 @@ function dropHint(reason: InboundDropReason): string {
|
|
|
786
793
|
}
|
|
787
794
|
}
|
|
788
795
|
|
|
796
|
+
function guardLoginRejections(client: KakaoTalkClient, onError: (err: unknown) => void): KakaoTalkClient {
|
|
797
|
+
return new Proxy(client, {
|
|
798
|
+
get(target, prop, receiver) {
|
|
799
|
+
const value: unknown = Reflect.get(target, prop, receiver)
|
|
800
|
+
if (typeof value !== 'function') return value
|
|
801
|
+
return (...args: unknown[]): unknown => {
|
|
802
|
+
const result: unknown = value.apply(target, args)
|
|
803
|
+
if (!(result instanceof Promise)) return result
|
|
804
|
+
return result.catch((err: unknown) => {
|
|
805
|
+
onError(err)
|
|
806
|
+
throw err
|
|
807
|
+
})
|
|
808
|
+
}
|
|
809
|
+
},
|
|
810
|
+
})
|
|
811
|
+
}
|
|
812
|
+
|
|
813
|
+
// The SDK maps every non-zero LOGINLIST status to KakaoTalkError code
|
|
814
|
+
// `login_rejected`, or `invalid_access_token` for -950. Transport failures
|
|
815
|
+
// carry other codes and stay retryable.
|
|
816
|
+
function kakaoLoginRejectionStatus(err: unknown): number | null {
|
|
817
|
+
if (!(err instanceof Error)) return null
|
|
818
|
+
const { code, serverStatus } = err as { code?: unknown; serverStatus?: unknown }
|
|
819
|
+
if (code !== 'login_rejected' && code !== 'invalid_access_token') return null
|
|
820
|
+
return typeof serverStatus === 'number' ? serverStatus : 0
|
|
821
|
+
}
|
|
822
|
+
|
|
789
823
|
function isKickoutError(err: unknown): boolean {
|
|
790
824
|
if (!(err instanceof Error)) return false
|
|
791
825
|
return err.message.includes('kicked') || err.message.includes('KICKOUT')
|
|
@@ -148,18 +148,28 @@ export function normalizeTeamsText(text: string): string {
|
|
|
148
148
|
// ONLY thing standing between the agent and answering its own message. That
|
|
149
149
|
// makes the comparison worth hardening: we fingerprint what we handed the SDK,
|
|
150
150
|
// but Teams stores messages as HTML, so the text comes back escaped-then-decoded
|
|
151
|
-
// and the two sides are not the same string.
|
|
152
|
-
//
|
|
153
|
-
// returns
|
|
154
|
-
//
|
|
155
|
-
//
|
|
156
|
-
// no
|
|
151
|
+
// and the two sides are not the same string. How many entity layers come back
|
|
152
|
+
// depends on the SDK and the message shape: a tag-free channel body without a
|
|
153
|
+
// `messagetype` returns still escaped, a typed body is decoded once, and older
|
|
154
|
+
// SDKs decoded lossily (`&lt;` -> `<`). Any mismatch would miss the
|
|
155
|
+
// reservation and route the agent's message back in as inbound. Decoding both
|
|
156
|
+
// sides until no entity layer remains gives the same key for every one of those
|
|
157
|
+
// shapes; on text holding no entities it is a no-op.
|
|
157
158
|
export function teamsEchoTextKey(text: string): string {
|
|
158
|
-
|
|
159
|
+
let decoded = text
|
|
160
|
+
for (;;) {
|
|
161
|
+
const next = decodeTeamsEntities(decoded)
|
|
162
|
+
if (next === decoded) break
|
|
163
|
+
decoded = next
|
|
164
|
+
}
|
|
165
|
+
return normalizeTeamsText(decoded)
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
function decodeTeamsEntities(text: string): string {
|
|
169
|
+
return text
|
|
159
170
|
.replace(/&/g, '&')
|
|
160
171
|
.replace(/</g, '<')
|
|
161
172
|
.replace(/>/g, '>')
|
|
162
173
|
.replace(/"/g, '"')
|
|
163
174
|
.replace(/'/g, "'")
|
|
164
|
-
return normalizeTeamsText(decoded)
|
|
165
175
|
}
|