typeclaw 0.51.0 → 0.52.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/types/agent/bash-sandbox-env.d.ts +2 -0
- package/dist/types/agent/bash-sandbox.d.ts +4 -0
- package/dist/types/agent/index.d.ts +5 -0
- package/dist/types/agent/multimodal/look-at.d.ts +1 -1
- package/dist/types/agent/plugin-tools.d.ts +4 -0
- package/dist/types/agent/prompt-cache-key.d.ts +1 -0
- package/dist/types/agent/session-tail.d.ts +12 -0
- package/dist/types/agent/subagents.d.ts +5 -0
- package/dist/types/agent/system-prompt-composition.d.ts +1 -0
- package/dist/types/agent/system-prompt.d.ts +2 -0
- package/dist/types/agent/tools/channel-disengage.d.ts +1 -1
- package/dist/types/agent/tools/channel-edit.d.ts +1 -1
- package/dist/types/agent/tools/channel-fetch-attachment.d.ts +1 -1
- package/dist/types/agent/tools/channel-handoff.d.ts +1 -1
- package/dist/types/agent/tools/channel-history.d.ts +1 -1
- package/dist/types/agent/tools/channel-react.d.ts +1 -1
- package/dist/types/agent/tools/channel-read.d.ts +10 -2
- package/dist/types/agent/tools/channel-reply.d.ts +1 -1
- package/dist/types/agent/tools/channel-send.d.ts +1 -1
- package/dist/types/agent/tools/channel-session-search.d.ts +1 -1
- package/dist/types/agent/tools/grant-role.d.ts +1 -1
- package/dist/types/agent/tools/post-github-review.d.ts +1 -1
- package/dist/types/agent/tools/restart.d.ts +1 -1
- package/dist/types/agent/tools/skip-response.d.ts +1 -1
- package/dist/types/agent/tools/spawn-subagent.d.ts +2 -1
- package/dist/types/agent/tools/stream-snapshot.d.ts +1 -1
- package/dist/types/agent/tools/subagent-cancel.d.ts +1 -1
- package/dist/types/agent/tools/subagent-output.d.ts +1 -1
- package/dist/types/agent/tools/todo/index.d.ts +1 -1
- package/dist/types/agent/tools/webfetch/adaptive-html.d.ts +3 -3
- package/dist/types/agent/tools/webfetch/strategies/readability-process.d.ts +48 -0
- package/dist/types/agent/tools/webfetch/tool.d.ts +2 -2
- package/dist/types/agent/tools/websearch.d.ts +1 -1
- package/dist/types/channels/adapters/github/auth-app.d.ts +25 -0
- package/dist/types/channels/adapters/github/auth-pat.d.ts +17 -0
- package/dist/types/channels/adapters/github/auth.d.ts +24 -0
- package/dist/types/channels/github-token-bridge.d.ts +4 -0
- package/dist/types/channels/lost-background-context.d.ts +2 -0
- package/dist/types/channels/persistence.d.ts +1 -0
- package/dist/types/channels/router.d.ts +5 -1
- package/dist/types/channels/types.d.ts +1 -0
- package/dist/types/coding-agent/tool.d.ts +1 -1
- package/dist/types/config/config.d.ts +20 -11
- package/dist/types/config/providers.d.ts +47 -0
- package/dist/types/eval/sandbox.d.ts +2 -0
- package/dist/types/git/resolve-identity.d.ts +2 -0
- package/dist/types/init/dockerfile.d.ts +1 -0
- package/dist/types/init/gitignore.d.ts +1 -1
- package/dist/types/permissions/builtins.d.ts +1 -0
- package/dist/types/plugin/types.d.ts +3 -0
- package/dist/types/sandbox/canonical-secrets.d.ts +2 -2
- package/dist/types/sandbox/coding-agent.d.ts +1 -1
- package/dist/types/sandbox/dependency-bins.d.ts +1 -0
- package/dist/types/sandbox/dev-source.d.ts +2 -2
- package/dist/types/sandbox/hidden-paths.d.ts +1 -0
- package/dist/types/sandbox/index.d.ts +1 -1
- package/dist/types/sandbox/policy.d.ts +3 -0
- package/dist/types/typevault/cli-path.d.ts +2 -0
- package/dist/types/typevault/envelope-store.d.ts +11 -0
- package/dist/types/typevault/lifecycle.d.ts +13 -0
- package/dist/types/typevault/vault.d.ts +27 -0
- package/package.json +8 -7
- package/scripts/test.ts +252 -0
- package/src/agent/bash-sandbox-env.ts +33 -1
- package/src/agent/bash-sandbox.ts +20 -6
- package/src/agent/index.ts +120 -31
- package/src/agent/multimodal/look-at.ts +1 -1
- package/src/agent/plugin-tools.ts +35 -1
- package/src/agent/prompt-cache-key.ts +26 -3
- package/src/agent/session-origin.ts +39 -18
- package/src/agent/session-tail.ts +28 -0
- package/src/agent/subagents.ts +21 -2
- package/src/agent/system-prompt-composition.ts +18 -0
- package/src/agent/system-prompt.ts +39 -1
- package/src/agent/tool-error-remediation.ts +18 -3
- package/src/agent/tools/channel-disengage.ts +1 -1
- package/src/agent/tools/channel-edit.ts +1 -1
- package/src/agent/tools/channel-fetch-attachment.ts +1 -1
- package/src/agent/tools/channel-handoff.ts +3 -2
- package/src/agent/tools/channel-history.ts +2 -1
- package/src/agent/tools/channel-react.ts +1 -1
- package/src/agent/tools/channel-read.ts +36 -3
- package/src/agent/tools/channel-reply.ts +1 -1
- package/src/agent/tools/channel-send.ts +4 -3
- package/src/agent/tools/channel-session-search.ts +13 -4
- package/src/agent/tools/grant-role.ts +1 -1
- package/src/agent/tools/post-github-review.ts +1 -1
- package/src/agent/tools/restart.ts +1 -1
- package/src/agent/tools/skip-response.ts +1 -1
- package/src/agent/tools/spawn-subagent.ts +15 -1
- package/src/agent/tools/stream-snapshot.ts +1 -1
- package/src/agent/tools/subagent-cancel.ts +1 -1
- package/src/agent/tools/subagent-output.ts +1 -1
- package/src/agent/tools/todo/index.ts +1 -1
- package/src/agent/tools/webfetch/adaptive-html.ts +6 -4
- package/src/agent/tools/webfetch/strategies/readability-child.ts +25 -0
- package/src/agent/tools/webfetch/strategies/readability-process.ts +185 -0
- package/src/agent/tools/webfetch/tool.ts +6 -5
- package/src/agent/tools/websearch.ts +1 -1
- package/src/browser/dockerfile.ts +1 -1
- package/src/browser/fill-secret.ts +92 -35
- package/src/browser/registry.ts +6 -6
- package/src/bundled-plugins/agent-messenger-cli-auth/command.ts +211 -0
- package/src/bundled-plugins/agent-messenger-cli-auth/index.ts +186 -0
- package/src/bundled-plugins/backup/index.ts +17 -2
- package/src/bundled-plugins/backup/runner.ts +37 -2
- package/src/bundled-plugins/browser-agent/browser-agent.ts +51 -14
- package/src/bundled-plugins/browser-agent/index.ts +12 -5
- package/src/bundled-plugins/managed-browser/index.ts +25 -2
- package/src/bundled-plugins/managed-browser/skills/browserskill/browserskill/SKILL.md +13 -5
- package/src/bundled-plugins/managed-browser/skills/omowright/omowright/SKILL.md +56 -5
- package/src/bundled-plugins/memory/README.md +23 -2
- package/src/bundled-plugins/memory/append-fragment.ts +133 -0
- package/src/bundled-plugins/memory/append-tool.ts +80 -149
- package/src/bundled-plugins/memory/dreaming.ts +2 -0
- package/src/bundled-plugins/memory/index.ts +33 -6
- package/src/bundled-plugins/memory/memory-logger.ts +133 -11
- package/src/bundled-plugins/memory/references/store-reference-tool.ts +56 -32
- package/src/bundled-plugins/memory/remember-tool.ts +81 -0
- package/src/bundled-plugins/memory/search-tool-hybrid.ts +91 -0
- package/src/bundled-plugins/memory/search-tool.ts +58 -12
- package/src/bundled-plugins/memory/stream-events.ts +2 -0
- package/src/bundled-plugins/memory/transcript-cursor.ts +30 -0
- package/src/bundled-plugins/memory/transcript-preload.ts +131 -26
- package/src/bundled-plugins/memory/transcript-view.ts +36 -0
- package/src/bundled-plugins/memory/watermark.ts +19 -10
- package/src/bundled-plugins/reviewer/reviewer.ts +20 -0
- package/src/bundled-plugins/security/policies/outbound-secret-scan.ts +3 -6
- package/src/bundled-plugins/security/policies/outbound-text.ts +20 -0
- package/src/bundled-plugins/security/policies/system-prompt-leak.ts +2 -7
- package/src/bundled-plugins/typevault/grants.ts +119 -0
- package/src/bundled-plugins/typevault/index.ts +152 -0
- package/src/bundled-plugins/typevault/request.ts +87 -0
- package/src/bundled-plugins/typevault/runtime.ts +45 -0
- package/src/bundled-plugins/typevault/skills/typevault/SKILL.md +65 -0
- package/src/channels/adapter-halt.ts +17 -0
- package/src/channels/adapters/github/history.ts +23 -2
- package/src/channels/adapters/github/inbound.ts +60 -1
- package/src/channels/adapters/github/index.ts +27 -5
- package/src/channels/adapters/github/reconcile-open-prs.ts +7 -1
- package/src/channels/adapters/kakaotalk-author-resolver.ts +7 -5
- package/src/channels/adapters/kakaotalk-channel-resolver.ts +45 -15
- package/src/channels/adapters/kakaotalk-classify.ts +7 -9
- package/src/channels/adapters/kakaotalk-list.ts +62 -0
- package/src/channels/adapters/kakaotalk-member-cache.ts +67 -0
- package/src/channels/adapters/kakaotalk-membership.ts +27 -10
- package/src/channels/adapters/kakaotalk-mention.ts +61 -0
- package/src/channels/adapters/kakaotalk.ts +159 -125
- package/src/channels/adapters/teams-classify.ts +18 -8
- package/src/channels/github-token-bridge.ts +13 -0
- package/src/channels/lost-background-context.ts +46 -0
- package/src/channels/manager.ts +52 -3
- package/src/channels/persistence.ts +5 -0
- package/src/channels/router.ts +120 -21
- package/src/channels/schema.ts +1 -1
- package/src/channels/types.ts +3 -0
- package/src/coding-agent/tool.ts +1 -1
- package/src/config/config.ts +20 -1
- package/src/config/providers.ts +65 -0
- package/src/container/start.ts +15 -2
- package/src/doctor/channel-checks.ts +33 -0
- package/src/doctor/checks.ts +12 -2
- package/src/eval/sandbox.ts +3 -0
- package/src/eval/tool.ts +1 -0
- package/src/git/resolve-identity.ts +67 -2
- package/src/git/system-commit.ts +7 -0
- package/src/init/dockerfile.ts +5 -1
- package/src/init/gitignore.ts +3 -3
- package/src/init/index.ts +1 -0
- package/src/init/models-dev.ts +2 -0
- package/src/init/validate-api-key.ts +5 -0
- package/src/migrations/secrets-v1-to-v2.ts +2 -0
- package/src/permissions/builtins.ts +8 -0
- package/src/plugin/types.ts +6 -0
- package/src/run/bundled-plugins.ts +12 -0
- package/src/run/channel-session-factory.ts +3 -0
- package/src/run/index.ts +13 -2
- package/src/sandbox/build.ts +1 -0
- package/src/sandbox/canonical-secrets.ts +6 -0
- package/src/sandbox/dependency-bins.ts +13 -1
- package/src/sandbox/dev-source.ts +21 -12
- package/src/sandbox/hidden-paths.ts +1 -1
- package/src/sandbox/index.ts +1 -0
- package/src/sandbox/policy.ts +5 -0
- package/src/secrets/hydrate.ts +4 -1
- package/src/secrets/storage.ts +10 -1
- package/src/server/command-runner.ts +4 -0
- package/src/server/index.ts +8 -1
- package/src/skills/typeclaw-config/SKILL.md +16 -0
- package/src/skills/typeclaw-memory/SKILL.md +3 -1
- package/src/skills/typeclaw-permissions/SKILL.md +8 -8
- package/src/skills/typeclaw-troubleshooting/SKILL.md +18 -1
- package/src/tunnels/active.ts +14 -0
- package/src/typevault/bash-cli.ts +18 -0
- package/src/typevault/cli-path.ts +11 -0
- package/src/typevault/envelope-helper.ts +17 -0
- package/src/typevault/envelope-store.ts +98 -0
- package/src/typevault/lifecycle.ts +132 -0
- package/src/typevault/prompt-tunnel.ts +33 -0
- package/src/typevault/redaction.ts +37 -0
- package/src/typevault/vault.ts +283 -0
- package/typeclaw.schema.json +40 -10
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
// This is an extractor view only. The source transcript and its replay
|
|
2
|
+
// signatures remain authoritative and are never rewritten.
|
|
3
|
+
export function projectTranscriptLine(line: string): string {
|
|
4
|
+
let entry: unknown
|
|
5
|
+
try {
|
|
6
|
+
entry = JSON.parse(line)
|
|
7
|
+
} catch (error) {
|
|
8
|
+
if (error instanceof SyntaxError) return line
|
|
9
|
+
throw error
|
|
10
|
+
}
|
|
11
|
+
if (!isRecord(entry) || !isRecord(entry.message)) return line
|
|
12
|
+
if (entry.message.role !== 'assistant') return line
|
|
13
|
+
|
|
14
|
+
const message = { ...entry.message }
|
|
15
|
+
for (const key of ['usage', 'api', 'provider', 'model', 'responseId']) delete message[key]
|
|
16
|
+
if (Array.isArray(message.content)) {
|
|
17
|
+
message.content = message.content.map((block: unknown) => {
|
|
18
|
+
if (!isRecord(block)) return block
|
|
19
|
+
if (block.type === 'toolCall') {
|
|
20
|
+
const content = { ...block }
|
|
21
|
+
delete content.thoughtSignature
|
|
22
|
+
return content
|
|
23
|
+
}
|
|
24
|
+
if (block.type !== 'text' && block.type !== 'thinking') return block
|
|
25
|
+
const content = { ...block }
|
|
26
|
+
delete content.thinkingSignature
|
|
27
|
+
delete content.textSignature
|
|
28
|
+
return content
|
|
29
|
+
})
|
|
30
|
+
}
|
|
31
|
+
return JSON.stringify({ ...entry, message })
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
35
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
|
36
|
+
}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { readdir } from 'node:fs/promises'
|
|
2
2
|
import { join } from 'node:path'
|
|
3
3
|
|
|
4
|
+
import type { StreamEvent } from './stream-events'
|
|
4
5
|
import { readEvents } from './stream-io'
|
|
5
6
|
|
|
6
7
|
// Daily stream files are named `YYYY-MM-DD.jsonl` (see `formatLocalDate` in
|
|
@@ -11,13 +12,8 @@ const DAILY_STREAM_NAME = /^\d{4}-\d{2}-\d{2}\.jsonl$/
|
|
|
11
12
|
export async function readWatermarkFromFile(streamFilePath: string, parentSessionId: string): Promise<string | null> {
|
|
12
13
|
const events = await readEvents(streamFilePath)
|
|
13
14
|
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
if ((event.type === 'fragment' || event.type === 'watermark') && event.source === parentSessionId) {
|
|
17
|
-
lastEntryId = event.entry
|
|
18
|
-
}
|
|
19
|
-
}
|
|
20
|
-
return lastEntryId
|
|
15
|
+
const progress = findProgress(events, parentSessionId)
|
|
16
|
+
return progress.checkpoint ?? progress.legacy
|
|
21
17
|
}
|
|
22
18
|
|
|
23
19
|
// Returns the latest watermark entry id for `parentSessionId` across all
|
|
@@ -47,9 +43,22 @@ export async function readLatestWatermark(memoryDir: string, parentSessionId: st
|
|
|
47
43
|
const dailyStreams = entries
|
|
48
44
|
.filter((name) => DAILY_STREAM_NAME.test(name))
|
|
49
45
|
.sort((a, b) => (a < b ? 1 : a > b ? -1 : 0))
|
|
46
|
+
let legacy: string | null = null
|
|
50
47
|
for (const name of dailyStreams) {
|
|
51
|
-
const
|
|
52
|
-
if (
|
|
48
|
+
const progress = findProgress(await readEvents(join(memoryDir, name)), parentSessionId)
|
|
49
|
+
if (progress.checkpoint !== null) return progress.checkpoint
|
|
50
|
+
legacy ??= progress.legacy
|
|
51
|
+
}
|
|
52
|
+
return legacy
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function findProgress(events: StreamEvent[], source: string): { checkpoint: string | null; legacy: string | null } {
|
|
56
|
+
let checkpoint: string | null = null
|
|
57
|
+
let legacy: string | null = null
|
|
58
|
+
for (const event of events) {
|
|
59
|
+
if (event.type === 'watermark' && event.source === source) checkpoint = event.entry
|
|
60
|
+
// Explicit captures have not evaluated the logger's pending transcript.
|
|
61
|
+
if (event.type === 'fragment' && event.kind !== 'explicit' && event.source === source) legacy = event.entry
|
|
53
62
|
}
|
|
54
|
-
return
|
|
63
|
+
return { checkpoint, legacy }
|
|
55
64
|
}
|
|
@@ -195,6 +195,12 @@ export const reviewerPayloadSchema = z
|
|
|
195
195
|
requestId: z.string().optional(),
|
|
196
196
|
prompt: z.string().optional(),
|
|
197
197
|
description: z.string().optional(),
|
|
198
|
+
skill: z
|
|
199
|
+
.enum(REVIEWER_SKILLS.map((skill) => skill.name))
|
|
200
|
+
.optional()
|
|
201
|
+
.describe(
|
|
202
|
+
'One curated review skill to preload. Omit for ambiguous or unspecified domains; load_skill remains available.',
|
|
203
|
+
),
|
|
198
204
|
reviewIdentity: reviewerReviewIdentitySchema.optional(),
|
|
199
205
|
})
|
|
200
206
|
.passthrough()
|
|
@@ -230,6 +236,20 @@ If none of the listed skills fit the target, load \`general\`. Keep the skill-se
|
|
|
230
236
|
...(options === undefined ? [] : [createReviewerCheckoutTool(options.resolveTokenForRepo)]),
|
|
231
237
|
],
|
|
232
238
|
payloadSchema: reviewerPayloadSchema,
|
|
239
|
+
handler: async ({ payload }, runSession) => {
|
|
240
|
+
const skill = REVIEWER_SKILLS.find((candidate) => candidate.name === payload.skill)
|
|
241
|
+
await runSession(
|
|
242
|
+
skill === undefined
|
|
243
|
+
? undefined
|
|
244
|
+
: {
|
|
245
|
+
systemPrompt:
|
|
246
|
+
`${REVIEWER_SYSTEM_PROMPT}\n\n## Preloaded review skill: ${skill.name}\n\n` +
|
|
247
|
+
'The following curated skill is already loaded. Apply it directly; skip the initial load_skill call. ' +
|
|
248
|
+
'Keep load_skill for an additional domain only when the target requires it.\n\n' +
|
|
249
|
+
skill.content,
|
|
250
|
+
},
|
|
251
|
+
)
|
|
252
|
+
},
|
|
233
253
|
visibility: 'public',
|
|
234
254
|
rosterDescription:
|
|
235
255
|
'deep read-only code/PR/plan review in a fresh context, returns a structured verdict; it does NOT post — you act on its findings',
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { SecuritySeverity } from '../permissions'
|
|
2
2
|
import type { SecurityBlock } from '../policy'
|
|
3
|
+
import { outboundTexts } from './outbound-text'
|
|
3
4
|
|
|
4
5
|
export const GUARD_OUTBOUND_SECRET = 'outboundSecret'
|
|
5
6
|
// Classified `high` (audience-leak axis): bypass posts credential-shaped
|
|
@@ -60,6 +61,7 @@ const PROCESS_ENV_TARGETS: ReadonlyArray<string> = [
|
|
|
60
61
|
'MOONSHOT_API_KEY',
|
|
61
62
|
'MOONSHOT_CODING_API_KEY',
|
|
62
63
|
'INCEPTION_API_KEY',
|
|
64
|
+
'EXAONE_API_KEY',
|
|
63
65
|
'GOOGLE_API_KEY',
|
|
64
66
|
'GEMINI_API_KEY',
|
|
65
67
|
'AWS_ACCESS_KEY_ID',
|
|
@@ -95,8 +97,6 @@ const ENV_KEY_RECON_MATCHERS: ReadonlyArray<readonly [name: string, pattern: Reg
|
|
|
95
97
|
(name) => [name, new RegExp(`\\b${name}\\b`)] as const,
|
|
96
98
|
)
|
|
97
99
|
|
|
98
|
-
const TEXT_KEYS = ['text', 'message', 'content', 'body']
|
|
99
|
-
|
|
100
100
|
export type OutboundSecretMatch = {
|
|
101
101
|
kind: string
|
|
102
102
|
source: 'signature' | 'process_env' | 'env_key_recon'
|
|
@@ -156,11 +156,8 @@ export function checkOutboundSecretGuard(options: {
|
|
|
156
156
|
env?: NodeJS.ProcessEnv
|
|
157
157
|
}): SecurityBlock | undefined {
|
|
158
158
|
const { tool, args } = options
|
|
159
|
-
if (tool !== 'channel_send' && tool !== 'channel_reply') return undefined
|
|
160
159
|
const env = options.env ?? process.env
|
|
161
|
-
for (const
|
|
162
|
-
const value = args[key]
|
|
163
|
-
if (typeof value !== 'string' || value.length === 0) continue
|
|
160
|
+
for (const value of outboundTexts(tool, args)) {
|
|
164
161
|
const matches = findOutboundSecrets(value, env)
|
|
165
162
|
if (matches.length === 0) continue
|
|
166
163
|
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { analyzeAgentMessengerCommand } from '@/bundled-plugins/agent-messenger-cli-auth/command'
|
|
2
|
+
|
|
3
|
+
const CHANNEL_TEXT_KEYS = ['text', 'message', 'content', 'body']
|
|
4
|
+
|
|
5
|
+
// The texts a tool call would post to a chat. A bot CLI command that
|
|
6
|
+
// agent-messenger-cli-auth would lend a channel token to posts its argv as the
|
|
7
|
+
// agent, so the audience-leak guards scan those arguments exactly as they scan
|
|
8
|
+
// channel_send text; otherwise that bash path would bypass them.
|
|
9
|
+
export function outboundTexts(tool: string, args: Record<string, unknown>): string[] {
|
|
10
|
+
if (tool === 'channel_send' || tool === 'channel_reply') {
|
|
11
|
+
return CHANNEL_TEXT_KEYS.map((key) => args[key]).filter(
|
|
12
|
+
(value): value is string => typeof value === 'string' && value.length > 0,
|
|
13
|
+
)
|
|
14
|
+
}
|
|
15
|
+
if (tool === 'bash' && typeof args.command === 'string') {
|
|
16
|
+
const decision = analyzeAgentMessengerCommand(args.command)
|
|
17
|
+
if (decision.kind === 'mint') return decision.args.filter((arg) => arg.length > 0)
|
|
18
|
+
}
|
|
19
|
+
return []
|
|
20
|
+
}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { SecuritySeverity } from '../permissions'
|
|
2
2
|
import type { SecurityBlock } from '../policy'
|
|
3
|
+
import { outboundTexts } from './outbound-text'
|
|
3
4
|
|
|
4
5
|
export const GUARD_SYSTEM_PROMPT_LEAK = 'systemPromptLeak'
|
|
5
6
|
// Classified `high` (audience-leak axis): bypass posts TypeClaw runtime
|
|
@@ -64,13 +65,7 @@ export function checkSystemPromptLeakGuard(options: {
|
|
|
64
65
|
args: Record<string, unknown>
|
|
65
66
|
}): SecurityBlock | undefined {
|
|
66
67
|
const { tool, args } = options
|
|
67
|
-
|
|
68
|
-
const candidates: string[] = []
|
|
69
|
-
for (const key of ['text', 'message', 'content', 'body']) {
|
|
70
|
-
const v = args[key]
|
|
71
|
-
if (typeof v === 'string' && v.length > 0) candidates.push(v)
|
|
72
|
-
}
|
|
73
|
-
for (const text of candidates) {
|
|
68
|
+
for (const text of outboundTexts(tool, args)) {
|
|
74
69
|
const hits = findSystemPromptLeak(text)
|
|
75
70
|
if (hits.length === 0) continue
|
|
76
71
|
const summary = hits.map((h) => h.label).join('; ')
|
|
@@ -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
|
+
}
|