typeclaw 0.48.3 → 0.48.5
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/package.json +2 -2
- package/scripts/dump-system-prompt.ts +146 -11
- package/src/agent/index.ts +6 -1
- package/src/agent/live-subagents.ts +15 -0
- package/src/agent/plugin-tools.ts +7 -0
- package/src/agent/session-origin.ts +104 -16
- package/src/agent/subagent-completion-reminder.ts +1 -1
- package/src/agent/subagent-drain.ts +11 -1
- package/src/agent/subagents.ts +52 -7
- package/src/agent/tool-file-safety.ts +14 -4
- package/src/agent/tools/runtime-notice.ts +29 -0
- package/src/agent/tools/spawn-subagent.ts +88 -7
- package/src/agent/tools/subagent-cancel.ts +1 -0
- package/src/agent/tools/subagent-output.ts +7 -2
- package/src/agent/tools/webfetch/adaptive-html.ts +319 -0
- package/src/agent/tools/webfetch/html-lexical.ts +841 -0
- package/src/agent/tools/webfetch/inline-style-visibility.ts +281 -0
- package/src/agent/tools/webfetch/strategies/readability.ts +306 -5
- package/src/agent/tools/webfetch/tool.ts +45 -2
- package/src/agent/tools/webfetch/types.ts +7 -0
- package/src/agent/turn-runner.ts +7 -3
- package/src/bundled-plugins/github-cli-auth/gh-command.ts +187 -8
- package/src/bundled-plugins/github-cli-auth/git-command.ts +497 -652
- package/src/bundled-plugins/memory/load-memory.ts +23 -27
- package/src/bundled-plugins/reviewer/reviewer.ts +32 -5
- package/src/bundled-plugins/reviewer/skills/code-review.ts +5 -3
- package/src/bundled-plugins/reviewer/skills/doc-review.ts +1 -1
- package/src/bundled-plugins/reviewer/skills/plan-review.ts +1 -1
- package/src/bundled-plugins/security/index.ts +1 -0
- package/src/bundled-plugins/security/policies/private-surface-read.ts +74 -18
- package/src/channels/router.ts +32 -47
- package/src/cli/hostd.ts +1 -1
- package/src/hostd/kakao-renewal-manager.ts +23 -11
- package/src/plugin/index.ts +1 -0
- package/src/plugin/types.ts +9 -10
- package/src/run/channel-session-factory.ts +3 -1
- package/src/run/index.ts +29 -29
- package/src/run/subagent-coalescing.ts +24 -0
- package/src/secrets/kakao-renewal.ts +123 -20
- package/src/server/index.ts +4 -1
- package/src/skills/typeclaw-channel-github/SKILL.md +6 -6
- package/src/skills/typeclaw-channel-instagram/SKILL.md +1 -1
- package/src/skills/typeclaw-channel-kakaotalk/SKILL.md +1 -1
- package/src/skills/typeclaw-channel-line/SKILL.md +1 -1
|
@@ -1,4 +1,9 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import {
|
|
2
|
+
renewCurrentAccount,
|
|
3
|
+
type AttemptLoginFn,
|
|
4
|
+
type RefreshOAuthTokenFn,
|
|
5
|
+
type RenewalMethod,
|
|
6
|
+
} from '@/secrets/kakao-renewal'
|
|
2
7
|
import { createKeyStore, type KeyStore } from '@/secrets/keys'
|
|
3
8
|
|
|
4
9
|
import { keysDir } from './paths'
|
|
@@ -19,7 +24,13 @@ export type KakaoRenewalStartInput = {
|
|
|
19
24
|
export type KakaoRenewalLogEvent =
|
|
20
25
|
| { kind: 'kakao-renewal-tick-start'; containerName: string }
|
|
21
26
|
| { kind: 'kakao-renewal-tick-skipped'; containerName: string; reason: string; ageMs?: number }
|
|
22
|
-
| {
|
|
27
|
+
| {
|
|
28
|
+
kind: 'kakao-renewal-tick-ok'
|
|
29
|
+
containerName: string
|
|
30
|
+
accountId: string
|
|
31
|
+
previousUpdatedAt: string
|
|
32
|
+
method?: RenewalMethod
|
|
33
|
+
}
|
|
23
34
|
| {
|
|
24
35
|
kind: 'kakao-renewal-tick-reauth-required'
|
|
25
36
|
containerName: string
|
|
@@ -37,13 +48,12 @@ export type KakaoRenewalManagerOptions = {
|
|
|
37
48
|
tickIntervalMs?: number
|
|
38
49
|
keyStoreFactory?: () => KeyStore
|
|
39
50
|
attemptLogin?: AttemptLoginFn
|
|
51
|
+
refreshOAuthToken?: RefreshOAuthTokenFn
|
|
40
52
|
schedule?: (fn: () => void, intervalMs: number) => { stop: () => void }
|
|
41
|
-
// Invoked after a successful renewal so the host can
|
|
42
|
-
// and the in-memory
|
|
43
|
-
//
|
|
44
|
-
//
|
|
45
|
-
// wires this to the same restart path the `restart` RPC uses; tests can
|
|
46
|
-
// observe it via a fake.
|
|
53
|
+
// Invoked after a successful renewal so the host can hot-reload the adapter
|
|
54
|
+
// and the in-memory LOCO client picks up the fresh tokens. Production falls
|
|
55
|
+
// back to recreating the container only when the reload transport fails;
|
|
56
|
+
// tests can observe the callback via a fake.
|
|
47
57
|
onRenewalOk?: (input: { containerName: string; cwd: string; accountId: string }) => Promise<void>
|
|
48
58
|
// Optional predicate: only start the renewal cron for containers whose
|
|
49
59
|
// `typeclaw.json` actually has a `channels.kakaotalk` block. Without this,
|
|
@@ -74,8 +84,8 @@ export function createKakaoRenewalManager(opts: KakaoRenewalManagerOptions = {})
|
|
|
74
84
|
// one finishes. The Map's value is the most recent input.
|
|
75
85
|
const latestInput = new Map<string, KakaoRenewalStartInput>()
|
|
76
86
|
// Track in-flight tick promises per container so stop()/drain() can await
|
|
77
|
-
// them. Without this, daemon shutdown abandons an in-flight
|
|
78
|
-
//
|
|
87
|
+
// them. Without this, daemon shutdown abandons an in-flight renewal HTTPS
|
|
88
|
+
// request mid-write.
|
|
79
89
|
const inFlight = new Map<string, Promise<void>>()
|
|
80
90
|
// Pending immediate-tick request: set when start() is called while a tick
|
|
81
91
|
// is in flight, so we re-fire one tick after the in-flight settles.
|
|
@@ -89,6 +99,7 @@ export function createKakaoRenewalManager(opts: KakaoRenewalManagerOptions = {})
|
|
|
89
99
|
agentDir: input.cwd,
|
|
90
100
|
keyStore,
|
|
91
101
|
...(opts.attemptLogin ? { attemptLogin: opts.attemptLogin } : {}),
|
|
102
|
+
...(opts.refreshOAuthToken ? { refreshOAuthToken: opts.refreshOAuthToken } : {}),
|
|
92
103
|
})
|
|
93
104
|
if (result.kind === 'skipped') {
|
|
94
105
|
log({
|
|
@@ -103,9 +114,10 @@ export function createKakaoRenewalManager(opts: KakaoRenewalManagerOptions = {})
|
|
|
103
114
|
containerName: input.containerName,
|
|
104
115
|
accountId: result.account_id,
|
|
105
116
|
previousUpdatedAt: result.previousUpdatedAt,
|
|
117
|
+
method: result.method,
|
|
106
118
|
})
|
|
107
119
|
// A tick that started before stop()/drain() (deregister, shutdown) or
|
|
108
|
-
// before a re-register with a different cwd can finish the slow
|
|
120
|
+
// before a re-register with a different cwd can finish the slow renewal
|
|
109
121
|
// here. Restarting a container that is no longer the current
|
|
110
122
|
// registration would resurrect a just-deregistered agent or fight a
|
|
111
123
|
// shutdown, so skip onRenewalOk unless this container+cwd is still the
|
package/src/plugin/index.ts
CHANGED
package/src/plugin/types.ts
CHANGED
|
@@ -65,19 +65,9 @@ export type RunSession = (override?: { userPrompt?: string }) => Promise<void>
|
|
|
65
65
|
// so a new shared field surfaces on both types in one edit. See
|
|
66
66
|
// `SubagentShared`'s doc-comment for the regression history.
|
|
67
67
|
//
|
|
68
|
-
// `inFlightKey` lives here only (not on the shared shape) because it is
|
|
69
|
-
// consumed exclusively by the `SubagentConsumer` via the
|
|
70
|
-
// `pluginSubagentByName` map, which holds the original plugin reference —
|
|
71
|
-
// the registry-flowing shim never needs to carry it.
|
|
72
68
|
export type Subagent<P = unknown> = SubagentShared<P> & {
|
|
73
69
|
tools?: BuiltinToolRef[]
|
|
74
70
|
customTools?: Tool<any>[]
|
|
75
|
-
// Coalescing key for the SubagentConsumer's in-flight set. Default is the
|
|
76
|
-
// subagent name alone (only one instance of the subagent runs at a time).
|
|
77
|
-
// Override to allow per-payload concurrency, e.g. memory-logger keyed by
|
|
78
|
-
// parentSessionId so different parent sessions run in parallel while
|
|
79
|
-
// duplicate runs against the same session deduplicate.
|
|
80
|
-
inFlightKey?: (payload: P) => string
|
|
81
71
|
}
|
|
82
72
|
|
|
83
73
|
// Cron job map keys are local; the runtime prefixes with `__plugin_<plugin-name>_`
|
|
@@ -220,12 +210,21 @@ export type SessionPromptEvent = {
|
|
|
220
210
|
|
|
221
211
|
// Fired for plugin-defined tools and TypeClaw-exposed system tools, including
|
|
222
212
|
// built-in pi tools (read/bash/edit/write/grep/find/ls) when plugins are wired.
|
|
213
|
+
//
|
|
214
|
+
// Set exclusively by TypeClaw's tool wrappers before a tool.before hook runs.
|
|
215
|
+
// Tool names and arguments are model/plugin controlled, so guards must not use
|
|
216
|
+
// either as evidence that a call is first-party.
|
|
217
|
+
export type ToolProvenance = 'first-party' | 'plugin'
|
|
218
|
+
|
|
223
219
|
export type ToolBeforeEvent = {
|
|
224
220
|
tool: string
|
|
225
221
|
sessionId: string
|
|
226
222
|
callId: string
|
|
227
223
|
args: Record<string, unknown>
|
|
228
224
|
origin?: SessionOrigin
|
|
225
|
+
// Internal wrapper-authenticated provenance. Omitted only by direct callers;
|
|
226
|
+
// guards must treat an omitted value as untrusted.
|
|
227
|
+
toolProvenance?: ToolProvenance
|
|
229
228
|
// The tool author's operand declarations (never model-controlled — set on the
|
|
230
229
|
// static Tool definition at registration). Carried so a guard that runs before
|
|
231
230
|
// the file-operand scanner (private-surface-read) can honor the same
|
|
@@ -6,7 +6,7 @@ import { createSession as defaultCreateSession } from '@/agent'
|
|
|
6
6
|
import type { LiveSessionRegistry } from '@/agent/live-sessions'
|
|
7
7
|
import type { LiveSubagentRegistry } from '@/agent/live-subagents'
|
|
8
8
|
import { sessionMetaPayload } from '@/agent/session-meta'
|
|
9
|
-
import type { CreateSessionForSubagent, SubagentRegistry } from '@/agent/subagents'
|
|
9
|
+
import type { CreateSessionForSubagent, SubagentCoalescer, SubagentRegistry } from '@/agent/subagents'
|
|
10
10
|
import { capJsonlFileInPlace } from '@/bundled-plugins/tool-result-cap/cap-jsonl'
|
|
11
11
|
import type { CapOptions } from '@/bundled-plugins/tool-result-cap/cap-result'
|
|
12
12
|
import type { CreateSessionForChannel, ChannelRouter } from '@/channels'
|
|
@@ -70,6 +70,7 @@ export type BuildChannelSessionFactoryDeps = {
|
|
|
70
70
|
// createSessionForSubagent, which needs channelManager.router. Same shape
|
|
71
71
|
// as `getChannelRouter` above.
|
|
72
72
|
liveSubagentRegistry?: LiveSubagentRegistry
|
|
73
|
+
subagentCoalescer?: SubagentCoalescer
|
|
73
74
|
subagentRegistry?: SubagentRegistry
|
|
74
75
|
getCreateSessionForSubagent?: () => CreateSessionForSubagent
|
|
75
76
|
liveSessionRegistry?: LiveSessionRegistry
|
|
@@ -136,6 +137,7 @@ export function buildChannelSessionFactory(deps: BuildChannelSessionFactoryDeps)
|
|
|
136
137
|
...(deps.permissions !== undefined ? { permissions: deps.permissions } : {}),
|
|
137
138
|
...(deps.reloadRoles !== undefined ? { reloadRoles: deps.reloadRoles } : {}),
|
|
138
139
|
...(deps.liveSubagentRegistry !== undefined ? { liveSubagentRegistry: deps.liveSubagentRegistry } : {}),
|
|
140
|
+
...(deps.subagentCoalescer !== undefined ? { subagentCoalescer: deps.subagentCoalescer } : {}),
|
|
139
141
|
...(deps.subagentRegistry !== undefined ? { subagentRegistry: deps.subagentRegistry } : {}),
|
|
140
142
|
...(deps.getCreateSessionForSubagent !== undefined
|
|
141
143
|
? { createSessionForSubagent: deps.getCreateSessionForSubagent() }
|
package/src/run/index.ts
CHANGED
|
@@ -17,6 +17,7 @@ import {
|
|
|
17
17
|
invokeSubagent,
|
|
18
18
|
isSubagentTimeoutError,
|
|
19
19
|
resolveSubagentProfile,
|
|
20
|
+
SubagentCoalescer,
|
|
20
21
|
type Subagent as InternalSubagent,
|
|
21
22
|
type SubagentConsumer,
|
|
22
23
|
type SubagentRegistry,
|
|
@@ -90,6 +91,7 @@ import { installFatalGuard } from './fatal-guard'
|
|
|
90
91
|
import { installLlmFetchObserver } from './llm-fetch-observer'
|
|
91
92
|
import { createPluginRuntime, type PluginRuntime, type PluginSubagentEntry } from './plugin-runtime'
|
|
92
93
|
import { logResourceReport } from './resource-report'
|
|
94
|
+
import { acquireSubagentCoalesceLease } from './subagent-coalescing'
|
|
93
95
|
|
|
94
96
|
type BunServer = ReturnType<Server['start']>
|
|
95
97
|
|
|
@@ -439,6 +441,7 @@ async function startAgentRuntime(
|
|
|
439
441
|
})
|
|
440
442
|
|
|
441
443
|
const liveSubagentRegistry = new LiveSubagentRegistry()
|
|
444
|
+
const subagentCoalescer = new SubagentCoalescer()
|
|
442
445
|
const liveSessionRegistry = new LiveSessionRegistry()
|
|
443
446
|
|
|
444
447
|
const channelManager = createChannelManagerFor({
|
|
@@ -459,6 +462,7 @@ async function startAgentRuntime(
|
|
|
459
462
|
permissions: pluginsLoaded.permissions,
|
|
460
463
|
reloadRoles: () => reloadRolesFromDisk(cwd),
|
|
461
464
|
liveSubagentRegistry,
|
|
465
|
+
subagentCoalescer,
|
|
462
466
|
liveSessionRegistry,
|
|
463
467
|
subagentRegistry: pluginRuntime.get().subagents,
|
|
464
468
|
getCreateSessionForSubagent: () => createSessionForSubagent,
|
|
@@ -569,6 +573,7 @@ async function startAgentRuntime(
|
|
|
569
573
|
...(entry.pluginSubagent.canSpawnSubagents === true
|
|
570
574
|
? {
|
|
571
575
|
liveSubagentRegistry,
|
|
576
|
+
subagentCoalescer,
|
|
572
577
|
subagentRegistry: snap.subagents,
|
|
573
578
|
createSessionForSubagent,
|
|
574
579
|
allowBackgroundFromSubagent,
|
|
@@ -637,17 +642,18 @@ async function startAgentRuntime(
|
|
|
637
642
|
getRegistry: () => pluginRuntime.get().subagents,
|
|
638
643
|
agentDir: cwd,
|
|
639
644
|
createSessionForSubagent,
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
const fn =
|
|
645
|
+
coalescer: subagentCoalescer,
|
|
646
|
+
inFlightKey: (name, payload, parentSessionId) => {
|
|
647
|
+
const fn = pluginRuntime.get().subagents[name]?.inFlightKey
|
|
643
648
|
if (fn !== undefined) {
|
|
644
649
|
try {
|
|
645
|
-
|
|
650
|
+
const key = `${name}:${fn(payload)}`
|
|
651
|
+
return parentSessionId === undefined ? key : `${parentSessionId}:${key}`
|
|
646
652
|
} catch {
|
|
647
|
-
return name
|
|
653
|
+
return parentSessionId === undefined ? name : `${parentSessionId}:${name}`
|
|
648
654
|
}
|
|
649
655
|
}
|
|
650
|
-
return name
|
|
656
|
+
return parentSessionId === undefined ? name : `${parentSessionId}:${name}`
|
|
651
657
|
},
|
|
652
658
|
})
|
|
653
659
|
registerBootCleanup(() => subagentConsumer.stop())
|
|
@@ -755,6 +761,7 @@ async function startAgentRuntime(
|
|
|
755
761
|
}
|
|
756
762
|
: {}),
|
|
757
763
|
liveSubagentRegistry,
|
|
764
|
+
subagentCoalescer,
|
|
758
765
|
subagentRegistry: pluginRuntime.get().subagents,
|
|
759
766
|
createSessionForSubagent,
|
|
760
767
|
...containerNameOpt,
|
|
@@ -911,23 +918,19 @@ async function startAgentRuntime(
|
|
|
911
918
|
// subagent declares one, else just `${name}`. Collisions resolve cleanly
|
|
912
919
|
// (logged + return) instead of rejecting, because callers from
|
|
913
920
|
// session.prompt are detached and a colliding spawn is a noop, not an error.
|
|
914
|
-
const directSpawnInFlight = new Set<string>()
|
|
915
921
|
const dispatchSpawnSubagent: CommandSpawnSubagent = async (name, payload, options) => {
|
|
916
|
-
const
|
|
917
|
-
const
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
}
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
if (directSpawnInFlight.has(coalesceKey)) {
|
|
927
|
-
console.warn(`[subagent] ${coalesceKey}: previous direct spawn still in progress, skipping`)
|
|
922
|
+
const registry = pluginRuntime.get().subagents
|
|
923
|
+
const lease = acquireSubagentCoalesceLease({
|
|
924
|
+
coalescer: subagentCoalescer,
|
|
925
|
+
subagentName: name,
|
|
926
|
+
subagent: registry[name],
|
|
927
|
+
payload,
|
|
928
|
+
...(options?.parentSessionId !== undefined ? { parentSessionId: options.parentSessionId } : {}),
|
|
929
|
+
})
|
|
930
|
+
if (lease === null) {
|
|
931
|
+
console.warn(`[subagent] ${name}: previous direct spawn still in progress, skipping`)
|
|
928
932
|
return
|
|
929
933
|
}
|
|
930
|
-
directSpawnInFlight.add(coalesceKey)
|
|
931
934
|
try {
|
|
932
935
|
// Resolve the spawning session's role from its origin so the subagent
|
|
933
936
|
// inherits it. Callers (hooks like session.idle) pass the parent origin
|
|
@@ -937,7 +940,6 @@ async function startAgentRuntime(
|
|
|
937
940
|
options?.spawnedByOrigin !== undefined
|
|
938
941
|
? pluginsLoaded.permissions.resolveRole(options.spawnedByOrigin)
|
|
939
942
|
: undefined
|
|
940
|
-
const registry = pluginRuntime.get().subagents
|
|
941
943
|
try {
|
|
942
944
|
await awaitWithSubagentTimeout(
|
|
943
945
|
invokeSubagent(name, {
|
|
@@ -952,18 +954,18 @@ async function startAgentRuntime(
|
|
|
952
954
|
...(options?.spawnedByOrigin !== undefined ? { spawnedByOrigin: options.spawnedByOrigin } : {}),
|
|
953
955
|
}),
|
|
954
956
|
name,
|
|
955
|
-
|
|
957
|
+
lease.key,
|
|
956
958
|
registry[name]?.timeoutMs,
|
|
957
959
|
)
|
|
958
960
|
} catch (err) {
|
|
959
961
|
if (isSubagentTimeoutError(err)) {
|
|
960
|
-
console.warn(`[subagent] ${
|
|
962
|
+
console.warn(`[subagent] ${lease.key} timed out after ${err.timeoutMs}ms; releasing coalesce key`)
|
|
961
963
|
return
|
|
962
964
|
}
|
|
963
965
|
throw err
|
|
964
966
|
}
|
|
965
967
|
} finally {
|
|
966
|
-
|
|
968
|
+
lease.release()
|
|
967
969
|
}
|
|
968
970
|
}
|
|
969
971
|
pluginsLoaded.setSpawnSubagent(dispatchSpawnSubagent)
|
|
@@ -1031,6 +1033,7 @@ async function startAgentRuntime(
|
|
|
1031
1033
|
commandRunnerFactory,
|
|
1032
1034
|
tunnelManager,
|
|
1033
1035
|
liveSubagentRegistry,
|
|
1036
|
+
subagentCoalescer,
|
|
1034
1037
|
createSessionForSubagent,
|
|
1035
1038
|
liveSessionRegistry,
|
|
1036
1039
|
...containerNameOpt,
|
|
@@ -1310,7 +1313,6 @@ type PluginOnlySubagentKeys = Exclude<keyof import('@/plugin').Subagent<any>, ke
|
|
|
1310
1313
|
const PLUGIN_ONLY_KEYS_DROPPED_BY_SHIM = {
|
|
1311
1314
|
tools: true,
|
|
1312
1315
|
customTools: true,
|
|
1313
|
-
inFlightKey: true,
|
|
1314
1316
|
} satisfies Record<PluginOnlySubagentKeys, true>
|
|
1315
1317
|
// Reference the table so it's not dead code. The value is a runtime no-op;
|
|
1316
1318
|
// the load-bearing work is the `satisfies` clause above which forces
|
|
@@ -1322,15 +1324,13 @@ function pluginSubagentShim(subagent: import('@/plugin').Subagent<any>): Interna
|
|
|
1322
1324
|
// `AgentSessionTools` internal-side; `customTools` similarly differs) are
|
|
1323
1325
|
// resolved later in `createSessionForSubagent` via the
|
|
1324
1326
|
// `pluginSubagentByShim` lookup, which recovers the original plugin
|
|
1325
|
-
// reference.
|
|
1326
|
-
// `pluginSubagentByName`, not through this shim's registry path. Every
|
|
1327
|
-
// other plugin-side field lives on `SubagentShared` and is structurally
|
|
1327
|
+
// reference. Every other plugin-side field lives on `SubagentShared` and is structurally
|
|
1328
1328
|
// assignable to the internal `Subagent`, so a rest-spread carries them
|
|
1329
1329
|
// verbatim — including `visibility` and `requiresSpecificPermission`,
|
|
1330
1330
|
// whose silent drop in the previous shim made every plugin-contributed
|
|
1331
1331
|
// public subagent (scout, explorer, operator) invisible to the
|
|
1332
1332
|
// `spawn_subagent` tool. The list of keys removed here is enforced
|
|
1333
1333
|
// exhaustive at compile time by `PLUGIN_ONLY_KEYS_DROPPED_BY_SHIM` above.
|
|
1334
|
-
const { tools: _tools, customTools: _customTools,
|
|
1334
|
+
const { tools: _tools, customTools: _customTools, ...shared } = subagent
|
|
1335
1335
|
return shared
|
|
1336
1336
|
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { type Subagent, SubagentCoalescer, subagentCoalesceKey } from '@/agent/subagents'
|
|
2
|
+
|
|
3
|
+
export type SubagentCoalesceLease = {
|
|
4
|
+
key: string
|
|
5
|
+
release: () => void
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
export function acquireSubagentCoalesceLease<P>(options: {
|
|
9
|
+
coalescer: SubagentCoalescer
|
|
10
|
+
subagentName: string
|
|
11
|
+
subagent: Subagent<P> | undefined
|
|
12
|
+
payload: P
|
|
13
|
+
parentSessionId?: string
|
|
14
|
+
}): SubagentCoalesceLease | null {
|
|
15
|
+
const key = subagentCoalesceKey({
|
|
16
|
+
subagentName: options.subagentName,
|
|
17
|
+
payload: options.payload,
|
|
18
|
+
fallbackKey: options.subagentName,
|
|
19
|
+
...(options.subagent?.inFlightKey !== undefined ? { inFlightKey: options.subagent.inFlightKey } : {}),
|
|
20
|
+
...(options.parentSessionId !== undefined ? { parentSessionId: options.parentSessionId } : {}),
|
|
21
|
+
})
|
|
22
|
+
if (!options.coalescer.tryAcquire(key)) return null
|
|
23
|
+
return { key, release: () => options.coalescer.release(key) }
|
|
24
|
+
}
|
|
@@ -1,6 +1,11 @@
|
|
|
1
1
|
import { join } from 'node:path'
|
|
2
2
|
|
|
3
|
-
import {
|
|
3
|
+
import {
|
|
4
|
+
attemptLogin as upstreamAttemptLogin,
|
|
5
|
+
KakaoOAuthRefreshError,
|
|
6
|
+
type KakaoDeviceType,
|
|
7
|
+
refreshKakaoOAuthToken as upstreamRefreshKakaoOAuthToken,
|
|
8
|
+
} from 'agent-messenger/kakaotalk'
|
|
4
9
|
|
|
5
10
|
import { decrypt, EncryptionError } from './encryption'
|
|
6
11
|
import { SecretsKakaoCredentialStore } from './kakao-store'
|
|
@@ -15,26 +20,44 @@ export const RENEWAL_THRESHOLD_MS = 5 * 24 * 60 * 60 * 1000
|
|
|
15
20
|
// for cron skips (host asleep, daemon respawning, etc.) and to absorb any
|
|
16
21
|
// downward drift in KakaoTalk's actual TTL.
|
|
17
22
|
|
|
23
|
+
type ReauthDecision = {
|
|
24
|
+
kind: 'reauth_required'
|
|
25
|
+
reason: 'no_password' | 'no_email' | 'key_missing' | 'decrypt_failed'
|
|
26
|
+
message: string
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
type PasswordRenewalDecision =
|
|
30
|
+
| ReauthDecision
|
|
31
|
+
| { kind: 'should_renew'; method: 'password'; account: AccountSnapshot & { email: string }; password: string }
|
|
32
|
+
|
|
18
33
|
export type RenewalDecision =
|
|
19
34
|
| { kind: 'skip'; reason: 'no_account' | 'fresh_enough'; ageMs?: number }
|
|
20
|
-
|
|
|
21
|
-
| { kind: 'should_renew';
|
|
35
|
+
| ReauthDecision
|
|
36
|
+
| { kind: 'should_renew'; method: 'oauth_refresh'; account: AccountSnapshot }
|
|
37
|
+
| PasswordRenewalDecision
|
|
22
38
|
|
|
23
39
|
export type AccountSnapshot = {
|
|
24
40
|
account_id: string
|
|
25
|
-
|
|
41
|
+
oauth_token: string
|
|
42
|
+
user_id: string
|
|
43
|
+
refresh_token?: string
|
|
26
44
|
device_uuid: string
|
|
27
45
|
device_type: KakaoDeviceType
|
|
46
|
+
auth_method?: 'login' | 'extract'
|
|
28
47
|
created_at: string
|
|
29
48
|
updated_at: string
|
|
49
|
+
email?: string
|
|
30
50
|
}
|
|
31
51
|
|
|
52
|
+
export type RenewalMethod = 'oauth_refresh' | 'password'
|
|
53
|
+
|
|
32
54
|
export type RenewalAttempt =
|
|
33
|
-
| { kind: 'ok'; account_id: string; previousUpdatedAt: string; nextUpdatedAt: string }
|
|
55
|
+
| { kind: 'ok'; account_id: string; previousUpdatedAt: string; nextUpdatedAt: string; method: RenewalMethod }
|
|
34
56
|
| { kind: 'reauth_required'; account_id: string; reason: string; message: string }
|
|
35
57
|
| { kind: 'transient_failure'; account_id: string; reason: string }
|
|
36
58
|
|
|
37
59
|
export type AttemptLoginFn = typeof upstreamAttemptLogin
|
|
60
|
+
export type RefreshOAuthTokenFn = typeof upstreamRefreshKakaoOAuthToken
|
|
38
61
|
|
|
39
62
|
export type RenewalContext = {
|
|
40
63
|
containerName: string
|
|
@@ -42,6 +65,7 @@ export type RenewalContext = {
|
|
|
42
65
|
keyStore: KeyStore
|
|
43
66
|
now?: () => number
|
|
44
67
|
attemptLogin?: AttemptLoginFn
|
|
68
|
+
refreshOAuthToken?: RefreshOAuthTokenFn
|
|
45
69
|
}
|
|
46
70
|
|
|
47
71
|
export async function decideRenewal(block: KakaoChannelBlock, ctx: RenewalContext): Promise<RenewalDecision> {
|
|
@@ -56,42 +80,64 @@ export async function decideRenewal(block: KakaoChannelBlock, ctx: RenewalContex
|
|
|
56
80
|
return { kind: 'skip', reason: 'fresh_enough', ageMs }
|
|
57
81
|
}
|
|
58
82
|
|
|
83
|
+
const snapshot = snapshotAccount(account)
|
|
84
|
+
if (account.refresh_token !== undefined) {
|
|
85
|
+
return { kind: 'should_renew', method: 'oauth_refresh', account: snapshot }
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
return decidePasswordRenewal(snapshot, account.encryptedPassword, ctx)
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function snapshotAccount(account: KakaoChannelBlock['accounts'][string]): AccountSnapshot {
|
|
92
|
+
return {
|
|
93
|
+
account_id: account.account_id,
|
|
94
|
+
oauth_token: account.oauth_token,
|
|
95
|
+
user_id: account.user_id,
|
|
96
|
+
...(account.refresh_token !== undefined ? { refresh_token: account.refresh_token } : {}),
|
|
97
|
+
device_uuid: account.device_uuid,
|
|
98
|
+
device_type: account.device_type,
|
|
99
|
+
...(account.auth_method !== undefined ? { auth_method: account.auth_method } : {}),
|
|
100
|
+
created_at: account.created_at,
|
|
101
|
+
updated_at: account.updated_at,
|
|
102
|
+
...(account.email !== undefined ? { email: account.email } : {}),
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
async function decidePasswordRenewal(
|
|
107
|
+
account: AccountSnapshot,
|
|
108
|
+
encryptedPassword: KakaoChannelBlock['accounts'][string]['encryptedPassword'],
|
|
109
|
+
ctx: RenewalContext,
|
|
110
|
+
): Promise<PasswordRenewalDecision> {
|
|
59
111
|
if (!account.email) {
|
|
60
112
|
return {
|
|
61
113
|
kind: 'reauth_required',
|
|
62
114
|
reason: 'no_email',
|
|
63
|
-
message: `KakaoTalk account ${
|
|
115
|
+
message: `KakaoTalk account ${account.account_id} has no stored email — run \`typeclaw channel reauth kakaotalk\`.`,
|
|
64
116
|
}
|
|
65
117
|
}
|
|
66
|
-
if (!
|
|
118
|
+
if (!encryptedPassword) {
|
|
67
119
|
return {
|
|
68
120
|
kind: 'reauth_required',
|
|
69
121
|
reason: 'no_password',
|
|
70
|
-
message: `KakaoTalk account ${
|
|
122
|
+
message: `KakaoTalk account ${account.account_id} has no stored password — run \`typeclaw channel reauth kakaotalk\`.`,
|
|
71
123
|
}
|
|
72
124
|
}
|
|
73
125
|
|
|
74
126
|
let plaintextPassword: string
|
|
75
127
|
try {
|
|
76
128
|
const key = await ctx.keyStore.read(ctx.containerName)
|
|
77
|
-
plaintextPassword = decrypt(
|
|
129
|
+
plaintextPassword = decrypt(encryptedPassword, key, {
|
|
78
130
|
containerName: ctx.containerName,
|
|
79
131
|
accountId: account.account_id,
|
|
80
132
|
})
|
|
81
133
|
} catch (err) {
|
|
82
|
-
return classifyDecryptFailure(err,
|
|
134
|
+
return classifyDecryptFailure(err, account.account_id)
|
|
83
135
|
}
|
|
84
136
|
|
|
85
137
|
return {
|
|
86
138
|
kind: 'should_renew',
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
email: account.email,
|
|
90
|
-
device_uuid: account.device_uuid,
|
|
91
|
-
device_type: account.device_type,
|
|
92
|
-
created_at: account.created_at,
|
|
93
|
-
updated_at: account.updated_at,
|
|
94
|
-
},
|
|
139
|
+
method: 'password',
|
|
140
|
+
account: { ...account, email: account.email },
|
|
95
141
|
password: plaintextPassword,
|
|
96
142
|
}
|
|
97
143
|
}
|
|
@@ -103,7 +149,7 @@ export async function renewCurrentAccount(
|
|
|
103
149
|
const backend = new SecretsBackend(secretsPath)
|
|
104
150
|
const block = backend.readChannelsSync()?.kakaotalk
|
|
105
151
|
const parsed = parseBlockOrEmpty(block)
|
|
106
|
-
|
|
152
|
+
let decision = await decideRenewal(parsed, ctx)
|
|
107
153
|
|
|
108
154
|
if (decision.kind === 'skip') {
|
|
109
155
|
return {
|
|
@@ -121,6 +167,62 @@ export async function renewCurrentAccount(
|
|
|
121
167
|
}
|
|
122
168
|
}
|
|
123
169
|
|
|
170
|
+
if (decision.method === 'oauth_refresh') {
|
|
171
|
+
const refreshOAuthToken = ctx.refreshOAuthToken ?? upstreamRefreshKakaoOAuthToken
|
|
172
|
+
try {
|
|
173
|
+
const refreshed = await refreshOAuthToken({
|
|
174
|
+
accessToken: decision.account.oauth_token,
|
|
175
|
+
refreshToken: decision.account.refresh_token ?? '',
|
|
176
|
+
deviceUuid: decision.account.device_uuid,
|
|
177
|
+
})
|
|
178
|
+
const store = new SecretsKakaoCredentialStore({ mode: 'host', secretsPath })
|
|
179
|
+
const nowIso = new Date().toISOString()
|
|
180
|
+
await store.setAccount({
|
|
181
|
+
account_id: decision.account.account_id,
|
|
182
|
+
oauth_token: refreshed.accessToken,
|
|
183
|
+
user_id: decision.account.user_id,
|
|
184
|
+
refresh_token: refreshed.refreshToken,
|
|
185
|
+
device_uuid: decision.account.device_uuid,
|
|
186
|
+
device_type: decision.account.device_type,
|
|
187
|
+
...(decision.account.auth_method !== undefined ? { auth_method: decision.account.auth_method } : {}),
|
|
188
|
+
created_at: decision.account.created_at,
|
|
189
|
+
updated_at: nowIso,
|
|
190
|
+
})
|
|
191
|
+
return {
|
|
192
|
+
kind: 'ok',
|
|
193
|
+
account_id: decision.account.account_id,
|
|
194
|
+
previousUpdatedAt: decision.account.updated_at,
|
|
195
|
+
nextUpdatedAt: nowIso,
|
|
196
|
+
method: 'oauth_refresh',
|
|
197
|
+
}
|
|
198
|
+
} catch (err) {
|
|
199
|
+
// Only a rejected or incomplete refresh credential justifies the heavier
|
|
200
|
+
// password login. Transport/server failures keep the refresh token in
|
|
201
|
+
// place and retry next tick rather than risk a passcode or captcha prompt.
|
|
202
|
+
if (
|
|
203
|
+
!(err instanceof KakaoOAuthRefreshError) ||
|
|
204
|
+
(err.code !== 'refresh_rejected' && err.code !== 'refresh_credentials_missing')
|
|
205
|
+
) {
|
|
206
|
+
return {
|
|
207
|
+
kind: 'transient_failure',
|
|
208
|
+
account_id: decision.account.account_id,
|
|
209
|
+
reason: err instanceof Error ? err.message : String(err),
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
const account = parsed.accounts[decision.account.account_id]
|
|
214
|
+
decision = await decidePasswordRenewal(decision.account, account?.encryptedPassword, ctx)
|
|
215
|
+
if (decision.kind === 'reauth_required') {
|
|
216
|
+
return {
|
|
217
|
+
kind: 'reauth_required',
|
|
218
|
+
account_id: parsed.currentAccount ?? '',
|
|
219
|
+
reason: decision.reason,
|
|
220
|
+
message: decision.message,
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
|
|
124
226
|
const attemptLogin = ctx.attemptLogin ?? upstreamAttemptLogin
|
|
125
227
|
const result = await attemptLogin(
|
|
126
228
|
decision.account.email,
|
|
@@ -166,6 +268,7 @@ export async function renewCurrentAccount(
|
|
|
166
268
|
account_id: decision.account.account_id,
|
|
167
269
|
previousUpdatedAt: decision.account.updated_at,
|
|
168
270
|
nextUpdatedAt: nowIso,
|
|
271
|
+
method: 'password',
|
|
169
272
|
}
|
|
170
273
|
}
|
|
171
274
|
|
|
@@ -174,7 +277,7 @@ function parseBlockOrEmpty(value: unknown): KakaoChannelBlock {
|
|
|
174
277
|
return value as KakaoChannelBlock
|
|
175
278
|
}
|
|
176
279
|
|
|
177
|
-
function classifyDecryptFailure(err: unknown, accountId: string):
|
|
280
|
+
function classifyDecryptFailure(err: unknown, accountId: string): ReauthDecision {
|
|
178
281
|
if (err instanceof KeyStoreError) {
|
|
179
282
|
if (err.code === 'missing') {
|
|
180
283
|
return {
|
package/src/server/index.ts
CHANGED
|
@@ -22,7 +22,7 @@ import { promptWithSameRefRetryOnly } from '@/agent/retry-same-ref'
|
|
|
22
22
|
import { sessionMetaPayload } from '@/agent/session-meta'
|
|
23
23
|
import type { SessionOrigin } from '@/agent/session-origin'
|
|
24
24
|
import { parseSubagentCompletedPayload, renderSubagentCompletionReminder } from '@/agent/subagent-completion-reminder'
|
|
25
|
-
import type { CreateSessionForSubagent } from '@/agent/subagents'
|
|
25
|
+
import type { CreateSessionForSubagent, SubagentCoalescer } from '@/agent/subagents'
|
|
26
26
|
import { TODO_CONTINUATION_SOURCE } from '@/agent/todo/continuation'
|
|
27
27
|
import {
|
|
28
28
|
armRestartKickForOrigin,
|
|
@@ -135,6 +135,7 @@ export type ServerOptions = {
|
|
|
135
135
|
// surface diverges across origin kinds — exactly the gap PR #281 flagged
|
|
136
136
|
// as out-of-scope follow-up.
|
|
137
137
|
liveSubagentRegistry?: LiveSubagentRegistry
|
|
138
|
+
subagentCoalescer?: SubagentCoalescer
|
|
138
139
|
createSessionForSubagent?: CreateSessionForSubagent
|
|
139
140
|
// Id-keyed registry of live AgentSessions, used by `/inspect` (and any
|
|
140
141
|
// future read-only session-event consumer) to subscribe to session
|
|
@@ -293,6 +294,7 @@ export function createServer({
|
|
|
293
294
|
claimController,
|
|
294
295
|
commandRunnerFactory,
|
|
295
296
|
liveSubagentRegistry,
|
|
297
|
+
subagentCoalescer,
|
|
296
298
|
createSessionForSubagent,
|
|
297
299
|
liveSessionRegistry,
|
|
298
300
|
}: ServerOptions) {
|
|
@@ -538,6 +540,7 @@ export function createServer({
|
|
|
538
540
|
...(containerName !== undefined ? { containerName } : {}),
|
|
539
541
|
...(runtimeVersion !== undefined ? { runtimeVersion } : {}),
|
|
540
542
|
...(liveSubagentRegistry !== undefined ? { liveSubagentRegistry } : {}),
|
|
543
|
+
...(subagentCoalescer !== undefined ? { subagentCoalescer } : {}),
|
|
541
544
|
...(subagentRegistry !== undefined ? { subagentRegistry } : {}),
|
|
542
545
|
...(createSessionForSubagent !== undefined ? { createSessionForSubagent } : {}),
|
|
543
546
|
})
|