typeclaw 0.50.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 +17 -0
- package/dist/types/agent/bash-sandbox-proc.d.ts +8 -0
- package/dist/types/agent/bash-sandbox.d.ts +98 -0
- package/dist/types/agent/compaction.d.ts +4 -4
- package/dist/types/agent/idle-compaction.d.ts +1 -0
- package/dist/types/agent/index.d.ts +10 -17
- package/dist/types/agent/multimodal/look-at.d.ts +1 -1
- package/dist/types/agent/output-allowance.d.ts +4 -0
- package/dist/types/agent/plugin-tools.d.ts +8 -75
- 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 +18 -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/ddg.d.ts +9 -0
- 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 +2 -2
- 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-review-check.d.ts +1 -1
- 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 +16 -50
- 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 +22 -0
- package/dist/types/config/providers.d.ts +50 -1
- package/dist/types/container/start.d.ts +1 -0
- package/dist/types/eval/cell.d.ts +26 -0
- package/dist/types/eval/config.d.ts +19 -0
- package/dist/types/eval/dispatch.d.ts +7 -0
- package/dist/types/eval/kernel.d.ts +28 -0
- package/dist/types/eval/process.d.ts +23 -0
- package/dist/types/eval/protocol.d.ts +34 -0
- package/dist/types/eval/sandbox.d.ts +12 -0
- package/dist/types/eval/tool.d.ts +17 -0
- package/dist/types/eval/wire.d.ts +33 -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/env-exposure.d.ts +2 -0
- 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 +136 -0
- package/src/agent/bash-sandbox-proc.ts +70 -0
- package/src/agent/bash-sandbox.ts +239 -0
- package/src/agent/compaction.ts +22 -10
- package/src/agent/idle-compaction.ts +7 -3
- package/src/agent/index.ts +185 -187
- package/src/agent/multimodal/look-at.ts +1 -1
- package/src/agent/output-allowance.ts +7 -0
- package/src/agent/plugin-tools.ts +64 -380
- package/src/agent/prompt-cache-key.ts +26 -3
- package/src/agent/session-origin.ts +41 -19
- package/src/agent/session-tail.ts +28 -0
- package/src/agent/subagent-completion-reminder.ts +2 -2
- package/src/agent/subagents.ts +21 -2
- package/src/agent/system-prompt-composition.ts +159 -0
- package/src/agent/system-prompt.ts +43 -5
- package/src/agent/todo/scope.ts +1 -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/ddg.ts +71 -11
- 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/agent/tools-without-local-file-operands.ts +4 -0
- package/src/browser/dockerfile.ts +1 -1
- package/src/browser/fill-secret.ts +364 -0
- 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/explorer/explorer.ts +1 -1
- package/src/bundled-plugins/github-cli-auth/gh-review-detect.ts +40 -16
- package/src/bundled-plugins/github-cli-auth/graphql-auth-nudge.ts +12 -7
- package/src/bundled-plugins/github-cli-auth/index.ts +10 -1
- package/src/bundled-plugins/managed-browser/index.ts +130 -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 +6 -1
- package/src/bundled-plugins/memory/index.ts +33 -6
- package/src/bundled-plugins/memory/load-memory.ts +2 -4
- package/src/bundled-plugins/memory/memory-logger.ts +200 -6
- 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 +208 -0
- package/src/bundled-plugins/memory/transcript-view.ts +36 -0
- package/src/bundled-plugins/memory/vector/hybrid.ts +25 -14
- 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/private-surface-read.ts +166 -201
- 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/discord-bot-reference.ts +5 -4
- package/src/channels/adapters/discord-bot.ts +1 -0
- package/src/channels/adapters/discord-classify.ts +8 -3
- package/src/channels/adapters/discord.ts +29 -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-review-check.ts +5 -1
- package/src/channels/github-review-verdict-coordinator.ts +68 -2
- 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 +208 -128
- package/src/channels/schema.ts +1 -1
- package/src/channels/subagent-completion-bridge.ts +3 -2
- package/src/channels/types.ts +3 -0
- package/src/cli/hostd.ts +3 -0
- package/src/coding-agent/tool.ts +1 -1
- package/src/config/config.ts +35 -1
- package/src/config/providers.ts +75 -4
- package/src/container/start.ts +52 -3
- package/src/doctor/channel-checks.ts +33 -0
- package/src/doctor/checks.ts +37 -18
- package/src/doctor/index.ts +48 -12
- package/src/doctor/operational-incidents.ts +16 -1
- package/src/doctor/plugin-bridge.ts +14 -1
- package/src/doctor/stage.ts +14 -0
- package/src/doctor/types.ts +6 -0
- package/src/eval/cell.ts +93 -0
- package/src/eval/config.ts +32 -0
- package/src/eval/dispatch.ts +67 -0
- package/src/eval/entry.ts +261 -0
- package/src/eval/kernel.ts +154 -0
- package/src/eval/process.ts +113 -0
- package/src/eval/protocol.ts +26 -0
- package/src/eval/redeclare.ts +174 -0
- package/src/eval/sandbox.ts +117 -0
- package/src/eval/tool.ts +99 -0
- package/src/eval/wire.ts +93 -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/operations/classify-tool-outcome.ts +1 -1
- package/src/permissions/builtins.ts +8 -0
- package/src/plugin/core-tool-names.ts +6 -1
- 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/env-exposure.ts +20 -0
- 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 +54 -12
- package/src/skills/typeclaw-config/SKILL.md +36 -2
- 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 +92 -10
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
import { join } from 'node:path'
|
|
2
|
+
|
|
3
|
+
import type { BashSandboxReveal } from '@/agent/bash-sandbox'
|
|
4
|
+
import { DEFAULT_SANDBOX_ENV } from '@/sandbox/policy'
|
|
5
|
+
import { agentSocketPath, projectIdentityPath, runtimeConfigRoot, typevaultDir } from '@/typevault/vault'
|
|
6
|
+
|
|
7
|
+
export const GRANT_TTL = '12h'
|
|
8
|
+
const GRANT_TTL_MS = 12 * 60 * 60 * 1000
|
|
9
|
+
// Reissue a little early so a long bash command never starts on a grant that
|
|
10
|
+
// expires mid-run.
|
|
11
|
+
const REISSUE_MARGIN_MS = 30 * 60 * 1000
|
|
12
|
+
|
|
13
|
+
export type GrantIssuer = {
|
|
14
|
+
issue: (request: { tier: string; label: string }) => Promise<string>
|
|
15
|
+
revoke: (label: string) => Promise<void>
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
type Held = { token: string; tier: string; label: string; issuedAt: number }
|
|
19
|
+
|
|
20
|
+
// Every grant gets its own label (`session:<id>:<n>`), so the audit trail names
|
|
21
|
+
// the session and a superseded grant can be revoked alone: typevault keeps one
|
|
22
|
+
// record per issuance, and revoking a shared label would also revoke the new
|
|
23
|
+
// grant.
|
|
24
|
+
export function createSessionGrants(issuer: GrantIssuer, now: () => number = Date.now) {
|
|
25
|
+
const held = new Map<string, Held>()
|
|
26
|
+
const queues = new Map<string, Promise<unknown>>()
|
|
27
|
+
let sequence = 0
|
|
28
|
+
|
|
29
|
+
// Grant transitions of one session run one at a time, so a caller never
|
|
30
|
+
// receives a token issued for another tier by a concurrent call.
|
|
31
|
+
const serialize = <T>(sessionId: string, task: () => Promise<T>): Promise<T> => {
|
|
32
|
+
const next = (queues.get(sessionId) ?? Promise.resolve()).then(task, task)
|
|
33
|
+
queues.set(
|
|
34
|
+
sessionId,
|
|
35
|
+
next.catch(() => {}),
|
|
36
|
+
)
|
|
37
|
+
return next
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
return {
|
|
41
|
+
tokenFor(sessionId: string, tier: string): Promise<string> {
|
|
42
|
+
return serialize(sessionId, async () => {
|
|
43
|
+
const current = held.get(sessionId)
|
|
44
|
+
if (
|
|
45
|
+
current !== undefined &&
|
|
46
|
+
current.tier === tier &&
|
|
47
|
+
now() - current.issuedAt < GRANT_TTL_MS - REISSUE_MARGIN_MS
|
|
48
|
+
) {
|
|
49
|
+
return current.token
|
|
50
|
+
}
|
|
51
|
+
// Revoke the old grant before exposing the replacement: after a role downgrade the
|
|
52
|
+
// old, higher-tier token must stop working even if it was copied. It
|
|
53
|
+
// stays held until revocation succeeds, so a retry revokes it again.
|
|
54
|
+
if (current !== undefined) {
|
|
55
|
+
await issuer.revoke(current.label)
|
|
56
|
+
held.delete(sessionId)
|
|
57
|
+
}
|
|
58
|
+
const label = `${sessionLabel(sessionId)}:${++sequence}`
|
|
59
|
+
const token = await issuer.issue({ tier, label })
|
|
60
|
+
held.set(sessionId, { token, tier, label, issuedAt: now() })
|
|
61
|
+
return token
|
|
62
|
+
})
|
|
63
|
+
},
|
|
64
|
+
heldToken(sessionId: string): string | undefined {
|
|
65
|
+
return held.get(sessionId)?.token
|
|
66
|
+
},
|
|
67
|
+
async end(sessionId: string): Promise<void> {
|
|
68
|
+
await serialize(sessionId, async () => {
|
|
69
|
+
const current = held.get(sessionId)
|
|
70
|
+
if (current === undefined) return
|
|
71
|
+
await issuer.revoke(current.label)
|
|
72
|
+
held.delete(sessionId)
|
|
73
|
+
})
|
|
74
|
+
queues.delete(sessionId)
|
|
75
|
+
},
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export function sessionLabel(sessionId: string): string {
|
|
80
|
+
return `session:${sessionId}`
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
// What model bash needs to reach the vault through a grant: the token, the
|
|
84
|
+
// ciphertext-only vault re-exposed read-only over its mask, and the daemon's
|
|
85
|
+
// agent socket bound where a client with the sandbox HOME looks for it. The
|
|
86
|
+
// admin sockets beside it and the agent's own key stay masked. The token and
|
|
87
|
+
// vault go under TypeClaw's names, read only by the `typevault` command
|
|
88
|
+
// (src/typevault/bash-cli.ts): a TYPEVAULT_* variable would steer every
|
|
89
|
+
// typevault CLI, a project's own included, to the agent's vault. The agent's
|
|
90
|
+
// project member identity, when provisioned, sits where any typevault CLI
|
|
91
|
+
// looks for this device's identity, so joining and opening a project's vault
|
|
92
|
+
// needs no password.
|
|
93
|
+
export function bashVaultAccess(
|
|
94
|
+
agentDir: string,
|
|
95
|
+
token: string,
|
|
96
|
+
options: { projectIdentity?: boolean } = {},
|
|
97
|
+
): { env: Record<string, string>; reveal: BashSandboxReveal } {
|
|
98
|
+
const sandboxConfigRoot = join(DEFAULT_SANDBOX_ENV.HOME ?? '/tmp', '.config')
|
|
99
|
+
return {
|
|
100
|
+
env: { TYPECLAW_VAULT_GRANT: token, TYPECLAW_VAULT_DIR: typevaultDir(agentDir) },
|
|
101
|
+
reveal: [
|
|
102
|
+
{ type: 'ro-bind', source: typevaultDir(agentDir), dest: typevaultDir(agentDir) },
|
|
103
|
+
{
|
|
104
|
+
type: 'ro-bind',
|
|
105
|
+
source: agentSocketPath(agentDir, runtimeConfigRoot(agentDir)),
|
|
106
|
+
dest: agentSocketPath(agentDir, sandboxConfigRoot),
|
|
107
|
+
},
|
|
108
|
+
...(options.projectIdentity === true
|
|
109
|
+
? [
|
|
110
|
+
{
|
|
111
|
+
type: 'ro-bind' as const,
|
|
112
|
+
source: projectIdentityPath(agentDir),
|
|
113
|
+
dest: join(sandboxConfigRoot, 'typevault', 'identity.json'),
|
|
114
|
+
},
|
|
115
|
+
]
|
|
116
|
+
: []),
|
|
117
|
+
],
|
|
118
|
+
}
|
|
119
|
+
}
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
import { join } from 'node:path'
|
|
2
|
+
|
|
3
|
+
import { createRedactor } from 'typevault/redact'
|
|
4
|
+
|
|
5
|
+
import { TYPECLAW_INTERNAL_BASH_ENV, TYPECLAW_INTERNAL_BASH_REVEAL } from '@/agent/plugin-tools'
|
|
6
|
+
import { getConfig } from '@/config'
|
|
7
|
+
import type { PermissionService } from '@/permissions'
|
|
8
|
+
import { BUILTIN_ROLE_NAMES, CORE_PERMISSIONS } from '@/permissions/builtins'
|
|
9
|
+
import { definePlugin, type Hooks } from '@/plugin'
|
|
10
|
+
import { isTypevaultMarkerFile } from '@/typevault/envelope-store'
|
|
11
|
+
import { vaultSecretValues } from '@/typevault/redaction'
|
|
12
|
+
import { ensureProjectIdentity, ensureRoleTiers, isRoleTier, projectMemberName, vaultAdmin } from '@/typevault/vault'
|
|
13
|
+
|
|
14
|
+
import { bashVaultAccess, createSessionGrants, GRANT_TTL } from './grants'
|
|
15
|
+
import { createVaultRequestTool, VAULT_REQUEST_TOOL } from './request'
|
|
16
|
+
import { activateVaultRuntime } from './runtime'
|
|
17
|
+
|
|
18
|
+
const SKILLS_ROOT = join(import.meta.dir, 'skills')
|
|
19
|
+
|
|
20
|
+
type SessionGrants = ReturnType<typeof createSessionGrants>
|
|
21
|
+
|
|
22
|
+
export default definePlugin({
|
|
23
|
+
plugin: async (ctx) => {
|
|
24
|
+
// Boot snapshot: typevault is restart-required, and start() settles whether
|
|
25
|
+
// secrets.json moved into the vault before the container boots.
|
|
26
|
+
const config = getConfig()
|
|
27
|
+
if (!config.typevault.enabled || !isTypevaultMarkerFile(join(ctx.agentDir, 'secrets.json'))) return {}
|
|
28
|
+
|
|
29
|
+
try {
|
|
30
|
+
const skipped = await ensureRoleTiers(ctx.agentDir, [...BUILTIN_ROLE_NAMES, ...Object.keys(config.roles ?? {})])
|
|
31
|
+
for (const role of skipped) {
|
|
32
|
+
ctx.logger.warn(`typevault: role "${role}" gets no vault tier (its name is reserved or not a valid tier name)`)
|
|
33
|
+
}
|
|
34
|
+
} catch (error) {
|
|
35
|
+
ctx.logger.error(`typevault: could not prepare role tiers; bash gets no vault grants: ${String(error)}`)
|
|
36
|
+
return {}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
let projectIdentity = true
|
|
40
|
+
try {
|
|
41
|
+
await ensureProjectIdentity(ctx.agentDir, projectMemberName(process.env.TYPECLAW_CONTAINER_NAME))
|
|
42
|
+
} catch (error) {
|
|
43
|
+
projectIdentity = false
|
|
44
|
+
ctx.logger.warn(`typevault: could not create the identity for joining project vaults: ${String(error)}`)
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const admin = vaultAdmin(ctx.agentDir, { promptPort: config.typevault.promptPort })
|
|
48
|
+
const grants = createSessionGrants({
|
|
49
|
+
issue: ({ tier, label }) => admin.grant({ tiers: [tier], ttl: GRANT_TTL, label }),
|
|
50
|
+
revoke: async (label) => {
|
|
51
|
+
await admin.revoke({ label })
|
|
52
|
+
},
|
|
53
|
+
})
|
|
54
|
+
const roles = new Map<string, string>()
|
|
55
|
+
activateVaultRuntime({ agentDir: ctx.agentDir, grants, roles })
|
|
56
|
+
const bashHook = vaultBashHook(ctx.agentDir, ctx.permissions, grants, ctx.logger, { projectIdentity })
|
|
57
|
+
|
|
58
|
+
return {
|
|
59
|
+
skillsDirs: [SKILLS_ROOT],
|
|
60
|
+
tools: { [VAULT_REQUEST_TOOL]: createVaultRequestTool() },
|
|
61
|
+
hooks: {
|
|
62
|
+
'session.prompt': (event) => {
|
|
63
|
+
event.prompt += `\n\n${CREDENTIALS_PROMPT}`
|
|
64
|
+
},
|
|
65
|
+
'tool.before': async (event, hookCtx) => {
|
|
66
|
+
// Tool contexts carry no origin, so remember the role each session
|
|
67
|
+
// last acted as for vault tools that run outside bash.
|
|
68
|
+
roles.set(event.sessionId, ctx.permissions.resolveRole(event.origin))
|
|
69
|
+
return bashHook(event, hookCtx)
|
|
70
|
+
},
|
|
71
|
+
'tool.after': vaultRedactHook(() => vaultSecretValues(ctx.agentDir), ctx.logger),
|
|
72
|
+
'session.end': async (event) => {
|
|
73
|
+
roles.delete(event.sessionId)
|
|
74
|
+
await grants.end(event.sessionId).catch((error: unknown) => {
|
|
75
|
+
ctx.logger.warn(`typevault: could not revoke the grant of session ${event.sessionId}: ${String(error)}`)
|
|
76
|
+
})
|
|
77
|
+
},
|
|
78
|
+
},
|
|
79
|
+
}
|
|
80
|
+
},
|
|
81
|
+
})
|
|
82
|
+
|
|
83
|
+
const CREDENTIALS_PROMPT = `## Credentials
|
|
84
|
+
|
|
85
|
+
This agent keeps usernames, passwords, API keys, and other credentials in its TypeVault vault (see the \`typevault\` skill).
|
|
86
|
+
|
|
87
|
+
- Never ask the user to paste a credential into chat, and never put a credential value in a subagent prompt. When one is missing, call \`${VAULT_REQUEST_TOOL}\` and send the user its link and match code.
|
|
88
|
+
- For a browser login, give \`browser\` the \`typevault://\` entry name, never the value. When \`browser\` reports a missing entry, request it with \`${VAULT_REQUEST_TOOL}\`, and spawn \`browser\` again once the user says it is stored.`
|
|
89
|
+
|
|
90
|
+
export function vaultBashHook(
|
|
91
|
+
agentDir: string,
|
|
92
|
+
permissions: PermissionService,
|
|
93
|
+
grants: SessionGrants,
|
|
94
|
+
logger: { warn: (msg: string) => void },
|
|
95
|
+
options: { projectIdentity?: boolean } = {},
|
|
96
|
+
): NonNullable<Hooks['tool.before']> {
|
|
97
|
+
return async (event) => {
|
|
98
|
+
if (event.tool !== 'bash' || !permissions.has(event.origin, CORE_PERMISSIONS.vaultUse)) return
|
|
99
|
+
const tier = permissions.resolveRole(event.origin)
|
|
100
|
+
if (!isRoleTier(tier)) return
|
|
101
|
+
let token: string
|
|
102
|
+
try {
|
|
103
|
+
token = await grants.tokenFor(event.sessionId, tier)
|
|
104
|
+
} catch (error) {
|
|
105
|
+
// The command still runs: without a grant `typevault` reports that it
|
|
106
|
+
// has none, which names the cause instead of failing unrelated bash.
|
|
107
|
+
logger.warn(`typevault: could not issue a grant for tier ${tier}: ${String(error)}`)
|
|
108
|
+
return
|
|
109
|
+
}
|
|
110
|
+
const access = bashVaultAccess(agentDir, token, options)
|
|
111
|
+
const existingEnv = event.args[TYPECLAW_INTERNAL_BASH_ENV]
|
|
112
|
+
event.args[TYPECLAW_INTERNAL_BASH_ENV] = {
|
|
113
|
+
...(existingEnv !== null && typeof existingEnv === 'object' ? (existingEnv as Record<string, string>) : {}),
|
|
114
|
+
...access.env,
|
|
115
|
+
}
|
|
116
|
+
const existingReveal = event.args[TYPECLAW_INTERNAL_BASH_REVEAL]
|
|
117
|
+
event.args[TYPECLAW_INTERNAL_BASH_REVEAL] = [
|
|
118
|
+
...(Array.isArray(existingReveal) ? existingReveal : []),
|
|
119
|
+
...access.reveal,
|
|
120
|
+
]
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
export const REDACTION_UNAVAILABLE =
|
|
125
|
+
'[typevault: output withheld because the secrets it may contain could not be redacted; retry once the vault is reachable]'
|
|
126
|
+
|
|
127
|
+
// `typevault run` already redacts its child's output; this second pass scrubs
|
|
128
|
+
// every secret the vault holds from every tool result, including a deliberate
|
|
129
|
+
// `get --reveal`, before it reaches the transcript. It fails closed: if the
|
|
130
|
+
// vault cannot be read, the output is withheld rather than passed through.
|
|
131
|
+
export function vaultRedactHook(
|
|
132
|
+
readValues: () => Promise<readonly string[]>,
|
|
133
|
+
logger: { warn: (msg: string) => void },
|
|
134
|
+
): NonNullable<Hooks['tool.after']> {
|
|
135
|
+
return async (event) => {
|
|
136
|
+
let values: readonly string[] | undefined
|
|
137
|
+
try {
|
|
138
|
+
values = await readValues()
|
|
139
|
+
} catch (error) {
|
|
140
|
+
logger.warn(
|
|
141
|
+
`typevault: withheld a tool result because vault secrets could not be read for redaction: ${String(error)}`,
|
|
142
|
+
)
|
|
143
|
+
event.result.content = [{ type: 'text', text: REDACTION_UNAVAILABLE }]
|
|
144
|
+
return
|
|
145
|
+
}
|
|
146
|
+
if (values.length === 0) return
|
|
147
|
+
const redactor = createRedactor(values)
|
|
148
|
+
for (const part of event.result.content) {
|
|
149
|
+
if (part.type === 'text') part.text = redactor.redact(part.text)
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
}
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import { z } from 'zod'
|
|
2
|
+
|
|
3
|
+
import { getConfig } from '@/config'
|
|
4
|
+
import { defineTool } from '@/plugin'
|
|
5
|
+
import { activeTunnelUrl } from '@/tunnels/active'
|
|
6
|
+
import { typevaultPromptTunnel } from '@/typevault/prompt-tunnel'
|
|
7
|
+
import { agentSocketPath, isRoleTier, runtimeConfigRoot } from '@/typevault/vault'
|
|
8
|
+
|
|
9
|
+
import { vaultRuntime } from './runtime'
|
|
10
|
+
|
|
11
|
+
export const VAULT_REQUEST_TOOL = 'vault_request'
|
|
12
|
+
|
|
13
|
+
const OpenedSchema = z.object({ id: z.string(), url: z.string(), code: z.string() })
|
|
14
|
+
const ErrorSchema = z.object({ error: z.object({ message: z.string() }) })
|
|
15
|
+
|
|
16
|
+
export type RequestStatus = 'opened' | 'tunnel-missing' | 'tunnel-starting' | 'failed'
|
|
17
|
+
|
|
18
|
+
export function promptTunnelUrl(): { status: 'ready'; url: string } | { status: 'tunnel-missing' | 'tunnel-starting' } {
|
|
19
|
+
const tunnel = typevaultPromptTunnel(getConfig())
|
|
20
|
+
if (tunnel === undefined) return { status: 'tunnel-missing' }
|
|
21
|
+
const url = activeTunnelUrl(tunnel.name)
|
|
22
|
+
return url === null ? { status: 'tunnel-starting' } : { status: 'ready', url }
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function createVaultRequestTool(tunnelUrl: typeof promptTunnelUrl = promptTunnelUrl) {
|
|
26
|
+
return defineTool({
|
|
27
|
+
description: [
|
|
28
|
+
"Ask the user to store a secret (API key, password, token) in this agent's vault through a one-time web page, so the value never passes through chat or your context.",
|
|
29
|
+
'Returns a link and a match code: send both to the user and tell them to check the code on the page before submitting.',
|
|
30
|
+
"The value is stored under `name` in your role's tier when they submit; nothing comes back to you. Check later with `typevault ls`.",
|
|
31
|
+
].join(' '),
|
|
32
|
+
parameters: z.object({
|
|
33
|
+
name: z.string().describe('Entry name, e.g. typevault://github/bot or typevault://openai'),
|
|
34
|
+
preset: z
|
|
35
|
+
.enum(['password', 'api_key', 'oauth', 'ssh', 'totp', 'note'])
|
|
36
|
+
.optional()
|
|
37
|
+
.describe('Fields the page asks for; default is a single secret value'),
|
|
38
|
+
reason: z.string().min(1).max(500).describe('Shown to the user on the page: what the secret is for'),
|
|
39
|
+
}),
|
|
40
|
+
fileOperands: { nonFile: ['name', 'preset', 'reason'] },
|
|
41
|
+
execute: async (args, ctx) => {
|
|
42
|
+
const runtime = vaultRuntime()
|
|
43
|
+
if (runtime === undefined) return result('failed', 'TypeVault is not enabled for this agent.')
|
|
44
|
+
const tunnel = tunnelUrl()
|
|
45
|
+
if (tunnel.status !== 'ready') {
|
|
46
|
+
return tunnel.status === 'tunnel-missing'
|
|
47
|
+
? result(
|
|
48
|
+
'tunnel-missing',
|
|
49
|
+
'The secret page has no public URL because TypeVault is not enabled at boot. Ask the operator to restart the agent.',
|
|
50
|
+
)
|
|
51
|
+
: result('tunnel-starting', 'The tunnel for the secret page has no public URL yet; try again in a moment.')
|
|
52
|
+
}
|
|
53
|
+
const role = runtime.roles.get(ctx.sessionId)
|
|
54
|
+
if (role === undefined || !isRoleTier(role)) return result('failed', 'This session has no vault tier.')
|
|
55
|
+
|
|
56
|
+
const token = await runtime.grants.tokenFor(ctx.sessionId, role)
|
|
57
|
+
const response = await fetch('http://typevault/v1/request', {
|
|
58
|
+
unix: agentSocketPath(runtime.agentDir, runtimeConfigRoot(runtime.agentDir)),
|
|
59
|
+
method: 'POST',
|
|
60
|
+
headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' },
|
|
61
|
+
body: JSON.stringify({ name: args.name, preset: args.preset, reason: args.reason }),
|
|
62
|
+
})
|
|
63
|
+
const body: unknown = await response.json().catch(() => undefined)
|
|
64
|
+
if (!response.ok) {
|
|
65
|
+
const error = ErrorSchema.safeParse(body)
|
|
66
|
+
return result(
|
|
67
|
+
'failed',
|
|
68
|
+
`Could not open the request: ${error.success ? error.data.error.message : response.status}`,
|
|
69
|
+
)
|
|
70
|
+
}
|
|
71
|
+
const opened = OpenedSchema.parse(body)
|
|
72
|
+
// The daemon only knows its loopback address; the page's path and token
|
|
73
|
+
// are what matter, so serve them from the tunnel's current origin.
|
|
74
|
+
const local = new URL(opened.url)
|
|
75
|
+
const link = new URL(`${local.pathname}${local.search}`, tunnel.url).toString()
|
|
76
|
+
return result(
|
|
77
|
+
'opened',
|
|
78
|
+
`Send the user this link and match code. It is stored as ${args.name} in tier "${role}" once they submit.\nLink: ${link}\nMatch code: ${opened.code}`,
|
|
79
|
+
{ link, code: opened.code },
|
|
80
|
+
)
|
|
81
|
+
},
|
|
82
|
+
})
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function result(status: RequestStatus, text: string, extra: Record<string, string> = {}) {
|
|
86
|
+
return { content: [{ type: 'text' as const, text }], details: { status, ...extra } }
|
|
87
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { defaultField, parseEntryRef, resolveField, TypeVaultError } from 'typevault'
|
|
2
|
+
|
|
3
|
+
import { grantAccess, isRoleTier } from '@/typevault/vault'
|
|
4
|
+
|
|
5
|
+
import type { createSessionGrants } from './grants'
|
|
6
|
+
|
|
7
|
+
type SessionGrants = ReturnType<typeof createSessionGrants>
|
|
8
|
+
|
|
9
|
+
// Shared with other bundled plugins (managed-browser's browser_fill_secret)
|
|
10
|
+
// so they read through the same per-session grant, scoped to the role the
|
|
11
|
+
// session last called a tool as, instead of minting their own.
|
|
12
|
+
type VaultRuntime = { agentDir: string; grants: SessionGrants; roles: Map<string, string> }
|
|
13
|
+
|
|
14
|
+
let active: VaultRuntime | undefined
|
|
15
|
+
|
|
16
|
+
export function activateVaultRuntime(runtime: VaultRuntime | undefined): void {
|
|
17
|
+
active = runtime
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function vaultRuntime(): VaultRuntime | undefined {
|
|
21
|
+
return active
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export type VaultRead = { ok: true; value: string } | { ok: false; reason: string }
|
|
25
|
+
|
|
26
|
+
export async function readVaultValue(sessionId: string, ref: string, reason: string): Promise<VaultRead> {
|
|
27
|
+
if (active === undefined) return { ok: false, reason: 'TypeVault is not enabled for this agent' }
|
|
28
|
+
const role = active.roles.get(sessionId)
|
|
29
|
+
if (role === undefined || !isRoleTier(role)) return { ok: false, reason: 'this session has no vault tier' }
|
|
30
|
+
try {
|
|
31
|
+
const { name, field } = parseEntryRef(ref)
|
|
32
|
+
const access = await grantAccess(active.agentDir, await active.grants.tokenFor(sessionId, role))
|
|
33
|
+
const entry = await access.get(name, reason)
|
|
34
|
+
const value =
|
|
35
|
+
field === undefined ? entry.fields[defaultField(entry.fields, ref)] : resolveField(entry.fields, field)
|
|
36
|
+
if (value === undefined) return { ok: false, reason: `${ref} has no such field` }
|
|
37
|
+
if (value.type !== 'secret' && value.type !== 'text') {
|
|
38
|
+
return { ok: false, reason: `${ref} is a ${value.type} field; use \`typevault run\` for it` }
|
|
39
|
+
}
|
|
40
|
+
return { ok: true, value: value.value }
|
|
41
|
+
} catch (error) {
|
|
42
|
+
if (error instanceof TypeVaultError) return { ok: false, reason: error.message }
|
|
43
|
+
throw error
|
|
44
|
+
}
|
|
45
|
+
}
|
|
@@ -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
|
+
}
|
|
@@ -14,6 +14,7 @@ export type DiscordMessagePointer = {
|
|
|
14
14
|
}
|
|
15
15
|
|
|
16
16
|
export async function enrichDiscordMessageReferences(args: {
|
|
17
|
+
adapter: 'discord' | 'discord-bot'
|
|
17
18
|
text: string
|
|
18
19
|
reply?: DiscordMessagePointer
|
|
19
20
|
fetchMessage: DiscordReferenceFetch
|
|
@@ -25,7 +26,7 @@ export async function enrichDiscordMessageReferences(args: {
|
|
|
25
26
|
if (args.reply !== undefined) {
|
|
26
27
|
const parent = await fetchSafely(args.fetchMessage, args.reply)
|
|
27
28
|
if (parent !== null) {
|
|
28
|
-
sources.push(toSource(parent))
|
|
29
|
+
sources.push(toSource(args.adapter, parent))
|
|
29
30
|
hasReply = true
|
|
30
31
|
}
|
|
31
32
|
}
|
|
@@ -33,7 +34,7 @@ export async function enrichDiscordMessageReferences(args: {
|
|
|
33
34
|
const links = extractDiscordMessageLinks(args.text).slice(0, args.linkLimit ?? 3)
|
|
34
35
|
for (const link of links) {
|
|
35
36
|
const message = await fetchSafely(args.fetchMessage, link)
|
|
36
|
-
if (message !== null) sources.push(toSource(message))
|
|
37
|
+
if (message !== null) sources.push(toSource(args.adapter, message))
|
|
37
38
|
}
|
|
38
39
|
|
|
39
40
|
if (sources.length === 0) return { text: args.text }
|
|
@@ -68,9 +69,9 @@ async function fetchSafely(
|
|
|
68
69
|
}
|
|
69
70
|
}
|
|
70
71
|
|
|
71
|
-
function toSource(message: DiscordResolvedReference): QuoteAnchorSource {
|
|
72
|
+
function toSource(adapter: 'discord' | 'discord-bot', message: DiscordResolvedReference): QuoteAnchorSource {
|
|
72
73
|
return {
|
|
73
|
-
adapter
|
|
74
|
+
adapter,
|
|
74
75
|
authorId: message.authorId,
|
|
75
76
|
authorName: message.authorName,
|
|
76
77
|
text: message.text,
|
|
@@ -1275,6 +1275,7 @@ export function createDiscordBotAdapter(options: DiscordBotAdapterOptions): Disc
|
|
|
1275
1275
|
const hintedText = addDiscordMentionHints(verdict.payload.text, mentionUserMap(event.mentions), { botUserId })
|
|
1276
1276
|
const replyMessageId = event.message_reference?.message_id
|
|
1277
1277
|
const referenceResult = await enrichDiscordMessageReferences({
|
|
1278
|
+
adapter: 'discord-bot',
|
|
1278
1279
|
text: hintedText,
|
|
1279
1280
|
...(replyMessageId !== undefined
|
|
1280
1281
|
? { reply: { channelId: event.message_reference?.channel_id ?? event.channel_id, messageId: replyMessageId } }
|
|
@@ -8,13 +8,18 @@ import { encodeDiscordReactionRef } from './discord-reactions'
|
|
|
8
8
|
|
|
9
9
|
export type DiscordInboundMessageEvent = DiscordGatewayMessageCreateEvent
|
|
10
10
|
|
|
11
|
-
// WORKAROUND: the USER-token SDK type omits `author.bot`
|
|
12
|
-
// `
|
|
13
|
-
// (`{ ...d }`), so
|
|
11
|
+
// WORKAROUND: the USER-token SDK type omits `author.bot`, `message_reference`,
|
|
12
|
+
// and `referenced_message`, but the listener spreads the raw Discord payload
|
|
13
|
+
// (`{ ...d }`), so they exist at runtime. Narrow locally instead of
|
|
14
14
|
// augmenting the SDK type globally — do not "simplify" this away.
|
|
15
15
|
export type RawDiscordMessageCreateEvent = DiscordGatewayMessageCreateEvent & {
|
|
16
16
|
author: { bot?: boolean }
|
|
17
17
|
message_reference?: { message_id?: string; channel_id?: string; guild_id?: string }
|
|
18
|
+
referenced_message?: {
|
|
19
|
+
id: string
|
|
20
|
+
content: string
|
|
21
|
+
author: { id: string; username: string; global_name?: string | null }
|
|
22
|
+
} | null
|
|
18
23
|
}
|
|
19
24
|
|
|
20
25
|
export type InboundDropReason = 'self_author' | 'no_user' | 'empty_content' | 'pre_connect'
|
|
@@ -40,11 +40,13 @@ import type { DiscordAccountRecord } from '@/secrets/schema'
|
|
|
40
40
|
|
|
41
41
|
import { describeError } from '../describe-error'
|
|
42
42
|
import { createDiscordAuthorResolver } from './discord-author-resolver'
|
|
43
|
+
import { enrichDiscordMessageReferences, type DiscordResolvedReference } from './discord-bot-reference'
|
|
43
44
|
import { createDiscordChannelResolver } from './discord-channel-resolver'
|
|
44
45
|
import {
|
|
45
46
|
classifyInbound,
|
|
46
47
|
type DiscordAttachmentCarrier,
|
|
47
48
|
type InboundDropReason,
|
|
49
|
+
type RawDiscordMessageCreateEvent,
|
|
48
50
|
splitDiscordAttachments,
|
|
49
51
|
} from './discord-classify'
|
|
50
52
|
import { createDiscordUserEditMessageCallback } from './discord-edit'
|
|
@@ -356,8 +358,24 @@ export function createDiscordAdapter(options: DiscordAdapterOptions): DiscordAda
|
|
|
356
358
|
mimetype: file.content_type,
|
|
357
359
|
}))
|
|
358
360
|
const room = verdict.payload.isDm ? undefined : await channelResolver.resolveRoom(verdict.payload.chat)
|
|
361
|
+
const raw = event as RawDiscordMessageCreateEvent
|
|
362
|
+
const replyMessageId = raw.message_reference?.message_id
|
|
363
|
+
const { referenceContext } = await enrichDiscordMessageReferences({
|
|
364
|
+
adapter: 'discord',
|
|
365
|
+
text: verdict.payload.text,
|
|
366
|
+
...(replyMessageId !== undefined
|
|
367
|
+
? { reply: { channelId: raw.message_reference?.channel_id ?? event.channel_id, messageId: replyMessageId } }
|
|
368
|
+
: {}),
|
|
369
|
+
// Reply gateway events already carry the parent inline; only links and
|
|
370
|
+
// replies Discord did not expand (deleted/inaccessible parents) cost a fetch.
|
|
371
|
+
fetchMessage: async (channelId, messageId) =>
|
|
372
|
+
raw.referenced_message?.id === messageId
|
|
373
|
+
? toResolvedReference(raw.referenced_message)
|
|
374
|
+
: toResolvedReference(await client.getMessage(channelId, messageId)),
|
|
375
|
+
})
|
|
359
376
|
const payload = {
|
|
360
377
|
...verdict.payload,
|
|
378
|
+
...(referenceContext !== undefined ? { referenceContext } : {}),
|
|
361
379
|
authorName: await authorResolver.resolve(verdict.payload.authorId),
|
|
362
380
|
...(room !== undefined ? { room } : {}),
|
|
363
381
|
...(attachments.length > 0 ? { attachments } : {}),
|
|
@@ -580,6 +598,17 @@ function parseDiscordTimestamp(timestamp: string): number {
|
|
|
580
598
|
return Number.isFinite(millis) ? millis : 0
|
|
581
599
|
}
|
|
582
600
|
|
|
601
|
+
function toResolvedReference(message: {
|
|
602
|
+
content: string
|
|
603
|
+
author: { id: string; username: string; global_name?: string | null }
|
|
604
|
+
}): DiscordResolvedReference {
|
|
605
|
+
return {
|
|
606
|
+
authorId: message.author.id,
|
|
607
|
+
authorName: message.author.global_name ?? message.author.username,
|
|
608
|
+
text: message.content,
|
|
609
|
+
}
|
|
610
|
+
}
|
|
611
|
+
|
|
583
612
|
const DISCORD_ATTACHMENT_HOSTS = new Set(['cdn.discordapp.com', 'media.discordapp.net'])
|
|
584
613
|
|
|
585
614
|
function clampLimit(requested: number, max: number): number {
|
|
@@ -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)
|