advisers 0.2.2 → 0.3.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/LICENSE +0 -0
- package/NOTICE +0 -0
- package/README-zh.md +11 -7
- package/README.md +16 -8
- package/THIRD-PARTY-NOTICES.md +1 -1
- package/bin/advisers.js +6347 -542
- package/index.js +1 -1
- package/lib/agent.js +529 -80
- package/lib/attachments.js +0 -0
- package/lib/audit-anchor.js +683 -0
- package/lib/backup.js +1345 -0
- package/lib/capture.js +0 -0
- package/lib/context-window.js +0 -0
- package/lib/digest.js +0 -0
- package/lib/doc-review.js +0 -0
- package/lib/egress.js +0 -0
- package/lib/error-codes.js +1373 -0
- package/lib/evidence.js +352 -43
- package/lib/fs-safe.js +347 -0
- package/lib/ical.js +0 -0
- package/lib/imap.js +6 -2
- package/lib/importers.js +0 -0
- package/lib/learning.js +0 -0
- package/lib/ledger-read.js +608 -0
- package/lib/mcp-server.js +331 -50
- package/lib/model.js +73 -1
- package/lib/node-warning-filter.js +15 -0
- package/lib/notify.js +13 -3
- package/lib/nudge.js +0 -0
- package/lib/ocr.js +29 -9
- package/lib/pdf.js +0 -0
- package/lib/pet-brief-store.js +0 -0
- package/lib/pet-brief.js +126 -64
- package/lib/receipt-verify.js +213 -15
- package/lib/relative-date.js +0 -0
- package/lib/remind.js +91 -36
- package/lib/research.js +0 -0
- package/lib/review.js +0 -0
- package/lib/routine.js +0 -0
- package/lib/safety/classifier.js +55 -2
- package/lib/safety/explain.js +0 -0
- package/lib/safety/index.js +0 -0
- package/lib/safety/redact.js +0 -0
- package/lib/safety/rules.js +28 -0
- package/lib/scheduler.js +0 -0
- package/lib/source.js +0 -0
- package/lib/sqlite.js +2302 -55
- package/lib/sync.js +398 -71
- package/lib/text-safe.js +229 -0
- package/lib/timestamp.js +29 -9
- package/lib/tos/index.js +1 -1
- package/lib/tos/manifest.json +6 -6
- package/lib/tos/privacy.zh-CN.md +12 -9
- package/lib/tos/safety.zh-CN.md +4 -3
- package/lib/tos/summary.zh-CN.md +3 -3
- package/lib/tos/terms.zh-CN.md +8 -6
- package/lib/tui/color.js +164 -0
- package/lib/tui/index.js +33 -0
- package/lib/tui/json.js +124 -0
- package/lib/tui/labels.js +50 -0
- package/lib/tui/policy.js +108 -0
- package/lib/tui/render.js +371 -0
- package/lib/tui/sanitize.js +142 -0
- package/lib/tui/text-file.js +116 -0
- package/lib/tui/width.js +577 -0
- package/lib/ui.js +0 -0
- package/lib/undo.js +0 -0
- package/lib/untrusted.js +186 -0
- package/lib/vault.js +0 -0
- package/package.json +6 -5
package/lib/agent.js
CHANGED
|
@@ -1,10 +1,18 @@
|
|
|
1
1
|
import { randomUUID } from 'node:crypto'
|
|
2
2
|
import { mkdir, readFile, readdir, writeFile } from 'node:fs/promises'
|
|
3
3
|
import { existsSync, lstatSync, realpathSync } from 'node:fs'
|
|
4
|
-
import { dirname, isAbsolute, relative, resolve } from 'node:path'
|
|
4
|
+
import { basename, dirname, isAbsolute, relative, resolve } from 'node:path'
|
|
5
5
|
import { chatCompletion, ModelError, resolveThinking } from './model.js'
|
|
6
6
|
import { backupBeforeWrite } from './undo.js'
|
|
7
7
|
import { estimateTokens } from './context-window.js'
|
|
8
|
+
import { classify } from './safety/index.js'
|
|
9
|
+
import {
|
|
10
|
+
UNTRUSTED_DATA_RULES,
|
|
11
|
+
truncateUntrusted,
|
|
12
|
+
wrapLegacyAttachmentText,
|
|
13
|
+
untrustedBlocks,
|
|
14
|
+
wrapUntrusted,
|
|
15
|
+
} from './untrusted.js'
|
|
8
16
|
|
|
9
17
|
const OFFICE_KINDS = ['docx', 'xlsx', 'pptx', 'xmind', 'mermaid', 'drawio']
|
|
10
18
|
const TEMPLATE_NAMES = ['weekly', 'budget', 'presentation', 'flow', 'mindmap', 'minutes', 'notice']
|
|
@@ -22,33 +30,225 @@ async function loadOffice() {
|
|
|
22
30
|
return officeModule
|
|
23
31
|
}
|
|
24
32
|
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
33
|
+
// ---------------------------------------------------------------------------
|
|
34
|
+
// file-tool policy (0.2.3 security foundation)
|
|
35
|
+
//
|
|
36
|
+
// Every file path an agent tool touches goes through one policy boundary:
|
|
37
|
+
// 1. lexical containment inside the workspace root (default: cwd);
|
|
38
|
+
// 2. realpath containment, so a symlink cannot escape that root;
|
|
39
|
+
// 3. sensitive-path denial (.ssh/.aws/.advisers/... anywhere, /etc/shadow,
|
|
40
|
+
// browser profiles, private keys, state backups);
|
|
41
|
+
// 4. write-only persistence denial (.bashrc, authorized_keys, autostart,
|
|
42
|
+
// cron/systemd units);
|
|
43
|
+
// 5. an explicit, default-off allow list (allowPaths) for deliberate
|
|
44
|
+
// out-of-workspace access. It can widen the workspace, never the
|
|
45
|
+
// sensitive or persistence lists.
|
|
46
|
+
// onToolAction receives one audit record per tool invocation (allowed or not)
|
|
47
|
+
// so the CLI can forward it to the append-only audit chain.
|
|
48
|
+
// ---------------------------------------------------------------------------
|
|
49
|
+
const DENY_SEGMENT_NAMES = new Set([
|
|
50
|
+
'.git', '.hg', '.svn', '.github', 'node_modules',
|
|
51
|
+
'.dsh', '.claude', '.advisers',
|
|
52
|
+
'.ssh', '.gnupg', '.aws', '.azure', '.kube', '.docker', '.mozilla', '.password-store',
|
|
53
|
+
'.cursor', '.codex',
|
|
54
|
+
])
|
|
55
|
+
const DENY_SEGMENT_SEQUENCES = Object.freeze([
|
|
56
|
+
['.config', 'gh'],
|
|
57
|
+
['.config', 'gcloud'],
|
|
58
|
+
['.config', 'hub'],
|
|
59
|
+
['.config', 'pip'],
|
|
60
|
+
['.config', 'op'],
|
|
61
|
+
['.config', '1password'],
|
|
62
|
+
['.config', 'google-chrome'],
|
|
63
|
+
['.config', 'chromium'],
|
|
64
|
+
['.config', 'microsoft-edge'],
|
|
65
|
+
['.config', 'brave-browser'],
|
|
66
|
+
['.config', 'bravesoftware'],
|
|
67
|
+
['.local', 'share', 'keyrings'],
|
|
68
|
+
['library', 'application support', 'google', 'chrome'],
|
|
69
|
+
['library', 'application support', 'firefox'],
|
|
70
|
+
['library', 'safari'],
|
|
71
|
+
['library', 'keychains'],
|
|
72
|
+
['appdata', 'roaming', 'mozilla', 'firefox'],
|
|
73
|
+
['appdata', 'local', 'google', 'chrome', 'user data'],
|
|
74
|
+
['appdata', 'local', 'microsoft', 'edge'],
|
|
75
|
+
])
|
|
76
|
+
const DENY_FILE_PATTERNS = Object.freeze([
|
|
77
|
+
/^\.env(?:\.|$)/u,
|
|
78
|
+
/^package\.json$/u,
|
|
79
|
+
/^pnpm-lock\.yaml$/u,
|
|
80
|
+
/^\.npmrc$/u,
|
|
81
|
+
/^soul\.md$/u,
|
|
82
|
+
/^state\.db(?:-|\.|$)/u,
|
|
83
|
+
/^\.netrc$/u,
|
|
84
|
+
/^\.pgpass$/u,
|
|
85
|
+
/^\.pypirc$/u,
|
|
86
|
+
/^\.git-credentials$/u,
|
|
87
|
+
/^credentials(?:\.json)?$/u,
|
|
88
|
+
/^id_(?:rsa|dsa|ecdsa|ed25519)$/u,
|
|
89
|
+
/\.(?:pem|key|p12|pfx|jks|keystore|kdbx|vault)$/u,
|
|
90
|
+
/^ntuser\.dat$/u,
|
|
91
|
+
])
|
|
92
|
+
const ABSOLUTE_DENY_PREFIXES = Object.freeze([
|
|
93
|
+
'/etc/shadow',
|
|
94
|
+
'/etc/gshadow',
|
|
95
|
+
'/etc/sudoers',
|
|
96
|
+
'/etc/sudoers.d',
|
|
97
|
+
'/etc/ssh',
|
|
98
|
+
'/root',
|
|
99
|
+
'/proc/self/environ',
|
|
100
|
+
'/proc/1/environ',
|
|
101
|
+
'/c:/windows/system32/config',
|
|
102
|
+
])
|
|
103
|
+
const WRITE_DENY_BASENAMES = new Set([
|
|
104
|
+
'.bashrc', '.bash_profile', '.bash_login', '.bash_logout', '.profile',
|
|
105
|
+
'.zshrc', '.zprofile', '.zshenv', '.cshrc', '.kshrc',
|
|
106
|
+
'authorized_keys', 'authorized_keys2', '.forward', '.rhosts', 'crontab',
|
|
107
|
+
])
|
|
108
|
+
const WRITE_DENY_SEQUENCES = Object.freeze([
|
|
109
|
+
['.config', 'autostart'],
|
|
110
|
+
['.config', 'systemd', 'user'],
|
|
111
|
+
['.local', 'share', 'systemd', 'user'],
|
|
112
|
+
['library', 'launchagents'],
|
|
113
|
+
['library', 'launchdaemons'],
|
|
114
|
+
])
|
|
115
|
+
const WRITE_DENY_FRAGMENTS = Object.freeze([
|
|
116
|
+
'/etc/cron',
|
|
117
|
+
'/etc/systemd/',
|
|
118
|
+
'/etc/profile',
|
|
119
|
+
'/etc/rc.local',
|
|
120
|
+
'/etc/init.d/',
|
|
121
|
+
'/start menu/programs/startup/',
|
|
122
|
+
])
|
|
123
|
+
|
|
124
|
+
/** Canonical policy view of a path (works for POSIX and Windows input). */
|
|
125
|
+
export function normalizePolicyPath(value) {
|
|
126
|
+
let text = String(value == null ? '' : value).replace(/\\/gu, '/')
|
|
127
|
+
text = text.replace(/^\/\/\?\/[a-zA-Z]:\//u, '/').replace(/^([a-zA-Z]):\//u, '/$1:/')
|
|
128
|
+
text = text.replace(/\/{2,}/gu, '/')
|
|
129
|
+
const segments = text
|
|
130
|
+
.split('/')
|
|
131
|
+
.filter(Boolean)
|
|
132
|
+
.map((segment) => segment.toLowerCase().replace(/[. ]+$/u, ''))
|
|
133
|
+
.filter(Boolean)
|
|
134
|
+
return { text: '/' + segments.join('/'), segments }
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
function hasSequence(segments, sequence) {
|
|
138
|
+
outer: for (let index = 0; index + sequence.length <= segments.length; index += 1) {
|
|
139
|
+
for (let offset = 0; offset < sequence.length; offset += 1) {
|
|
140
|
+
if (segments[index + offset] !== sequence[offset]) continue outer
|
|
141
|
+
}
|
|
142
|
+
return true
|
|
143
|
+
}
|
|
144
|
+
return false
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* Reason a path is sensitive, or null. Pure: no filesystem access, so tests
|
|
149
|
+
* can feed Windows/UNC/8.3-style samples on any platform.
|
|
150
|
+
*/
|
|
151
|
+
export function sensitivePathReason(value, { action = 'read' } = {}) {
|
|
152
|
+
const { text, segments } = normalizePolicyPath(value)
|
|
153
|
+
if (!segments.length) return null
|
|
154
|
+
for (const name of DENY_SEGMENT_NAMES) {
|
|
155
|
+
if (segments.includes(name)) return { code: 'SENSITIVE_PATH', reason: name + ' is protected' }
|
|
156
|
+
}
|
|
157
|
+
for (const sequence of DENY_SEGMENT_SEQUENCES) {
|
|
158
|
+
if (hasSequence(segments, sequence)) return { code: 'SENSITIVE_PATH', reason: sequence.join('/') + ' is protected' }
|
|
159
|
+
}
|
|
160
|
+
const base = segments[segments.length - 1]
|
|
161
|
+
for (const pattern of DENY_FILE_PATTERNS) {
|
|
162
|
+
if (pattern.test(base)) return { code: 'SENSITIVE_PATH', reason: base + ' is protected' }
|
|
163
|
+
}
|
|
164
|
+
for (const prefix of ABSOLUTE_DENY_PREFIXES) {
|
|
165
|
+
if (text === prefix || text.startsWith(prefix + '/')) return { code: 'SENSITIVE_PATH', reason: prefix + ' is protected' }
|
|
166
|
+
}
|
|
167
|
+
if (action === 'write') {
|
|
168
|
+
if (WRITE_DENY_BASENAMES.has(base)) return { code: 'PERSISTENCE_WRITE', reason: base + ' is a persistence target and cannot be written by tools' }
|
|
169
|
+
for (const sequence of WRITE_DENY_SEQUENCES) {
|
|
170
|
+
if (hasSequence(segments, sequence)) return { code: 'PERSISTENCE_WRITE', reason: sequence.join('/') + ' is a persistence location' }
|
|
171
|
+
}
|
|
172
|
+
for (const fragment of WRITE_DENY_FRAGMENTS) {
|
|
173
|
+
if (text.startsWith(fragment) || text.includes(fragment)) return { code: 'PERSISTENCE_WRITE', reason: fragment + ' is a persistence location' }
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
return null
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
function policyError(code, message) {
|
|
180
|
+
const error = new Error(message)
|
|
181
|
+
error.code = code
|
|
182
|
+
error.policy = true
|
|
183
|
+
return error
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
function nearestRealPath(absPath) {
|
|
187
|
+
let current = absPath
|
|
188
|
+
const tail = []
|
|
189
|
+
for (let depth = 0; depth < 128; depth += 1) {
|
|
190
|
+
try {
|
|
191
|
+
return resolve(realpathSync(current), ...tail)
|
|
192
|
+
} catch (error) {
|
|
193
|
+
if (error?.code !== 'ENOENT' && error?.code !== 'ENOTDIR') throw error
|
|
194
|
+
const parent = dirname(current)
|
|
195
|
+
if (parent === current) throw error
|
|
196
|
+
tail.unshift(basename(current))
|
|
197
|
+
current = parent
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
throw policyError('PATH_RESOLVE', 'cannot resolve path: ' + absPath)
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
function isInsideRoot(root, candidate) {
|
|
204
|
+
if (candidate === root) return true
|
|
205
|
+
const rel = relative(root, candidate)
|
|
206
|
+
return Boolean(rel) && !rel.startsWith('..') && !isAbsolute(rel)
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/**
|
|
210
|
+
* Resolve a tool path through the policy boundary and return the real target.
|
|
211
|
+
* Throws an Error with a stable .code:
|
|
212
|
+
* PATH_REQUIRED | WORKSPACE_MISSING | WORKSPACE_MISMATCH | OUTSIDE_WORKSPACE |
|
|
213
|
+
* SYMLINK_ESCAPE | SENSITIVE_PATH | PERSISTENCE_WRITE | SYMLINK_TARGET
|
|
214
|
+
*/
|
|
215
|
+
export function resolveToolPath(input, options = {}) {
|
|
216
|
+
const cwd = options.cwd || process.cwd()
|
|
217
|
+
if (typeof input !== 'string' || !input.trim()) throw policyError('PATH_REQUIRED', 'path is required')
|
|
218
|
+
const rootLexical = resolve(options.workspaceRoot || cwd)
|
|
219
|
+
let root
|
|
220
|
+
try {
|
|
221
|
+
root = realpathSync(rootLexical)
|
|
222
|
+
} catch {
|
|
223
|
+
throw policyError('WORKSPACE_MISSING', 'workspace root does not exist: ' + rootLexical)
|
|
224
|
+
}
|
|
225
|
+
let base
|
|
226
|
+
try {
|
|
227
|
+
base = realpathSync(resolve(cwd))
|
|
228
|
+
} catch {
|
|
229
|
+
throw policyError('WORKSPACE_MISSING', 'working directory does not exist: ' + cwd)
|
|
230
|
+
}
|
|
231
|
+
if (!isInsideRoot(root, base)) throw policyError('WORKSPACE_MISMATCH', 'working directory is outside the workspace root')
|
|
232
|
+
const allowPaths = Array.isArray(options.allowPaths) ? options.allowPaths : []
|
|
233
|
+
const allowedRoots = allowPaths
|
|
234
|
+
.filter((entry) => typeof entry === 'string' && entry.trim())
|
|
235
|
+
.map((entry) => resolve(rootLexical, entry))
|
|
236
|
+
const isExplicitlyAllowed = (candidate) => allowedRoots.some((allowed) => isInsideRoot(allowed, candidate))
|
|
237
|
+
const abs = resolve(base, input)
|
|
238
|
+
if (!isInsideRoot(root, abs) && !isExplicitlyAllowed(abs)) {
|
|
239
|
+
throw policyError('OUTSIDE_WORKSPACE', 'path escapes workspace: ' + input)
|
|
240
|
+
}
|
|
241
|
+
const real = nearestRealPath(abs)
|
|
242
|
+
if (!isInsideRoot(root, real) && !isExplicitlyAllowed(real)) {
|
|
243
|
+
throw policyError('SYMLINK_ESCAPE', 'path escapes workspace through a symlink: ' + input)
|
|
244
|
+
}
|
|
245
|
+
const action = options.action === 'write' ? 'write' : 'read'
|
|
246
|
+
const denied = sensitivePathReason(abs, { action }) || sensitivePathReason(real, { action })
|
|
247
|
+
if (denied) throw policyError(denied.code, 'path is protected: ' + denied.reason)
|
|
248
|
+
if (action === 'write' && existsSync(abs) && lstatSync(abs).isSymbolicLink()) {
|
|
249
|
+
throw policyError('SYMLINK_TARGET', 'symlink target is not allowed: ' + input)
|
|
250
|
+
}
|
|
251
|
+
return real
|
|
52
252
|
}
|
|
53
253
|
|
|
54
254
|
function tool(name, description, properties, required = []) {
|
|
@@ -136,13 +336,13 @@ function validateTemplate(name, data) {
|
|
|
136
336
|
if (name === 'notice' && (!data.title || !data.issuer || !Array.isArray(data.recipients) || !Array.isArray(data.body) || !data.signer || !data.date)) throw new Error('notice data requires title, issuer, recipients[], body[], signer, date')
|
|
137
337
|
}
|
|
138
338
|
|
|
139
|
-
async function runOfficeTool(name, args,
|
|
339
|
+
async function runOfficeTool(name, args, policy, backupDir) {
|
|
140
340
|
const office = await loadOffice()
|
|
141
|
-
const out =
|
|
341
|
+
const out = policy.resolve(args.out, 'write')
|
|
142
342
|
await mkdir(dirname(out), { recursive: true })
|
|
143
343
|
let spec
|
|
144
344
|
if (name === 'office_build') {
|
|
145
|
-
if (!OFFICE_KINDS.includes(args.kind)) throw new Error(
|
|
345
|
+
if (!OFFICE_KINDS.includes(args.kind)) throw new Error('unsupported kind: ' + args.kind)
|
|
146
346
|
spec = args.spec
|
|
147
347
|
if (args.kind === 'xmind' && (!Array.isArray(spec?.branches) || spec.branches.length === 0)) {
|
|
148
348
|
throw new Error('xmind spec requires a non-empty branches array: [{label, children: string[]}]')
|
|
@@ -160,7 +360,7 @@ async function runOfficeTool(name, args, cwd, backupDir) {
|
|
|
160
360
|
throw new Error('diagram spec requires nodes: [{id,label}]')
|
|
161
361
|
}
|
|
162
362
|
} else {
|
|
163
|
-
if (!TEMPLATE_NAMES.includes(args.name)) throw new Error(
|
|
363
|
+
if (!TEMPLATE_NAMES.includes(args.name)) throw new Error('unsupported template: ' + args.name)
|
|
164
364
|
validateTemplate(args.name, args.data)
|
|
165
365
|
spec = args.name === 'weekly' ? office.weeklyReport(args.data)
|
|
166
366
|
: args.name === 'budget' ? office.budget(args.data)
|
|
@@ -179,111 +379,192 @@ async function runOfficeTool(name, args, cwd, backupDir) {
|
|
|
179
379
|
else if (kind === 'xmind') { buffer = await office.buildXmind(spec); result = await office.validateXmind(buffer) }
|
|
180
380
|
else if (kind === 'drawio') { buffer = Buffer.from(office.buildDrawio(spec)); result = { ok: true, missing: [] } }
|
|
181
381
|
else { buffer = Buffer.from(office.buildMermaid(spec)); result = { ok: true, missing: [] } }
|
|
182
|
-
await backupBeforeWrite(out, { cwd, backupDir })
|
|
382
|
+
await backupBeforeWrite(policy.lexical(args.out), { cwd: policy.cwd, backupDir })
|
|
183
383
|
await writeFile(out, buffer)
|
|
184
384
|
return { ok: result.ok, artifact: true, path: out, bytes: buffer.length, missing: result.missing ?? [] }
|
|
185
385
|
}
|
|
186
386
|
|
|
187
|
-
function
|
|
387
|
+
function toolPathSpec(name, args) {
|
|
388
|
+
const value = args && typeof args === 'object' ? args : {}
|
|
389
|
+
if (name === 'office_build' || name === 'office_template') return { action: 'write', input: value.out }
|
|
390
|
+
if (name === 'office_edit') return { action: 'write', input: value.out || value.path }
|
|
391
|
+
if (name === 'file_write') return { action: 'write', input: value.path }
|
|
392
|
+
if (name === 'file_read' || name === 'office_read' || name === 'office_check') return { action: 'read', input: value.path }
|
|
393
|
+
if (name === 'file_list') return { action: 'read', input: value.dir == null ? '.' : value.dir }
|
|
394
|
+
return null
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
function createToolPolicy(options = {}) {
|
|
398
|
+
const cwd = options.cwd || process.cwd()
|
|
399
|
+
const workspaceRoot = options.workspaceRoot
|
|
400
|
+
const allowPaths = Array.isArray(options.allowPaths) ? options.allowPaths : []
|
|
401
|
+
const onToolAction = typeof options.onToolAction === 'function' ? options.onToolAction : null
|
|
402
|
+
const turnId = options.turnId
|
|
403
|
+
let root = null
|
|
404
|
+
try { root = realpathSync(resolve(workspaceRoot || cwd)) } catch { root = null }
|
|
405
|
+
return {
|
|
406
|
+
cwd,
|
|
407
|
+
workspaceRoot,
|
|
408
|
+
allowPaths,
|
|
409
|
+
root,
|
|
410
|
+
resolve(input, action) {
|
|
411
|
+
return resolveToolPath(input, { cwd, workspaceRoot, allowPaths, action })
|
|
412
|
+
},
|
|
413
|
+
/** Lexical path inside the workspace (used for undo manifests). */
|
|
414
|
+
lexical(input) {
|
|
415
|
+
return resolve(cwd, input)
|
|
416
|
+
},
|
|
417
|
+
async audit(entry) {
|
|
418
|
+
if (!onToolAction) return
|
|
419
|
+
let relativePath = null
|
|
420
|
+
if (root && typeof entry.path === 'string') {
|
|
421
|
+
const rel = relative(root, entry.path)
|
|
422
|
+
if (rel && !rel.startsWith('..') && !isAbsolute(rel)) relativePath = rel
|
|
423
|
+
}
|
|
424
|
+
try {
|
|
425
|
+
await onToolAction({ ...entry, relativePath, turnId: turnId || null, at: new Date().toISOString() })
|
|
426
|
+
} catch {}
|
|
427
|
+
},
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
function writeTarget(name, args, policy) {
|
|
188
432
|
try {
|
|
189
|
-
|
|
190
|
-
if (
|
|
191
|
-
|
|
433
|
+
const spec = toolPathSpec(name, args)
|
|
434
|
+
if (!spec || spec.action !== 'write') return null
|
|
435
|
+
return policy.resolve(spec.input, 'write')
|
|
192
436
|
} catch {
|
|
193
437
|
return null
|
|
194
438
|
}
|
|
195
|
-
return null
|
|
196
439
|
}
|
|
197
440
|
|
|
198
|
-
|
|
199
|
-
|
|
441
|
+
async function executeToolInner(name, args, policy, options) {
|
|
442
|
+
const cwd = policy.cwd
|
|
443
|
+
const backupDir = options.backupDir
|
|
444
|
+
if (name === 'office_build' || name === 'office_template') return runOfficeTool(name, args, policy, backupDir)
|
|
200
445
|
if (name === 'file_write') {
|
|
201
446
|
if (typeof args.content !== 'string' || Buffer.byteLength(args.content) > MAX_FILE_BYTES) throw new Error('content is missing or too large')
|
|
202
|
-
const path =
|
|
447
|
+
const path = policy.resolve(args.path, 'write')
|
|
203
448
|
await mkdir(dirname(path), { recursive: true })
|
|
204
|
-
await backupBeforeWrite(path, { cwd, backupDir })
|
|
449
|
+
await backupBeforeWrite(policy.lexical(args.path), { cwd, backupDir })
|
|
205
450
|
await writeFile(path, args.content)
|
|
206
451
|
return { ok: true, artifact: true, path, bytes: Buffer.byteLength(args.content) }
|
|
207
452
|
}
|
|
208
453
|
if (name === 'file_read') {
|
|
209
|
-
const path =
|
|
454
|
+
const path = policy.resolve(args.path, 'read')
|
|
210
455
|
const content = await readFile(path, 'utf8')
|
|
211
456
|
if (Buffer.byteLength(content) > MAX_FILE_BYTES) throw new Error('file is too large')
|
|
212
457
|
return { ok: true, artifact: false, path, content }
|
|
213
458
|
}
|
|
214
459
|
if (name === 'office_edit') {
|
|
215
|
-
const source =
|
|
216
|
-
const target =
|
|
460
|
+
const source = policy.resolve(args.path, 'read')
|
|
461
|
+
const target = policy.resolve(args.out || args.path, 'write')
|
|
462
|
+
const targetLexical = policy.lexical(args.out || args.path)
|
|
217
463
|
const office = await loadOffice()
|
|
218
464
|
const ext = source.split('.').pop()?.toLowerCase()
|
|
219
465
|
if (!['docx', 'xlsx', 'pptx'].includes(ext)) throw new Error('office_edit supports docx/xlsx/pptx')
|
|
220
466
|
const result = await office.editOffice(await readFile(source), ext, args.ops)
|
|
221
467
|
if (!result.ok) throw new Error(result.error || 'edit failed')
|
|
222
468
|
await mkdir(dirname(target), { recursive: true })
|
|
223
|
-
await backupBeforeWrite(
|
|
469
|
+
await backupBeforeWrite(targetLexical, { cwd, backupDir })
|
|
224
470
|
await writeFile(target, result.buffer)
|
|
225
471
|
return { ok: true, artifact: true, path: target, bytes: result.buffer.length, changes: result.changes }
|
|
226
472
|
}
|
|
227
473
|
if (name === 'office_check') {
|
|
228
474
|
const office = await loadOffice()
|
|
229
|
-
const target =
|
|
475
|
+
const target = policy.resolve(args.path, 'read')
|
|
230
476
|
const kind = String(args.path).split('.').pop()?.toLowerCase()
|
|
231
477
|
if (!['docx', 'xlsx', 'pptx'].includes(kind)) throw new Error('office_check supports docx/xlsx/pptx')
|
|
232
478
|
return { ok: true, artifact: false, result: await office.checkOffice(await readFile(target), kind) }
|
|
233
479
|
}
|
|
234
480
|
if (name === 'office_read') {
|
|
235
|
-
const target =
|
|
481
|
+
const target = policy.resolve(args.path, 'read')
|
|
236
482
|
const office = await loadOffice()
|
|
237
483
|
const doc = await office.readOffice(await readFile(target))
|
|
238
484
|
const text = office.officeToText(doc, Math.min(Number(args.max_chars) || 20_000, 50_000))
|
|
239
485
|
return { ok: true, artifact: false, kind: doc.kind, text }
|
|
240
486
|
}
|
|
241
487
|
if (name === 'commitment_add') {
|
|
242
|
-
if (!ledger || !matterId) throw new Error('commitment_add requires a ledger and matter')
|
|
243
|
-
const commitment = ledger.addCommitment({
|
|
244
|
-
matterId,
|
|
488
|
+
if (!options.ledger || !options.matterId) throw new Error('commitment_add requires a ledger and matter')
|
|
489
|
+
const commitment = options.ledger.addCommitment({
|
|
490
|
+
matterId: options.matterId,
|
|
245
491
|
debtor: args.debtor === 'agent' ? 'agent' : 'user',
|
|
246
492
|
creditor: args.creditor || /(?:发给|给|向|对)([\u4e00-\u9fa5A-Za-z0-9_]{1,12})/.exec(args.action)?.[1] || 'someone',
|
|
247
493
|
action: args.action,
|
|
248
494
|
dueAt: args.dueAt,
|
|
249
495
|
capability: 'todo',
|
|
250
|
-
evidence: [{ sessionId: turnId || 'local', turnId: turnId || 'local', quote: args.quote }],
|
|
496
|
+
evidence: [{ sessionId: options.turnId || 'local', turnId: options.turnId || 'local', quote: args.quote }],
|
|
251
497
|
})
|
|
252
498
|
return { ok: true, artifact: false, commitment }
|
|
253
499
|
}
|
|
254
500
|
if (name === 'memory_propose') {
|
|
255
|
-
if (!store) throw new Error('memory_propose requires a sqlite store')
|
|
256
|
-
if (!userText || !userText.includes(args.quote)) throw new Error('evidence quote not verbatim in the current user message')
|
|
501
|
+
if (!options.store) throw new Error('memory_propose requires a sqlite store')
|
|
502
|
+
if (!options.userText || !options.userText.includes(args.quote)) throw new Error('evidence quote not verbatim in the current user message')
|
|
257
503
|
const payload = args.kind === 'fact'
|
|
258
|
-
? { subject: args.subject || 'user', predicate: args.predicate, object: args.object, matterId }
|
|
504
|
+
? { subject: args.subject || 'user', predicate: args.predicate, object: args.object, matterId: options.matterId }
|
|
259
505
|
: args.kind === 'preference'
|
|
260
|
-
? { kind: args.preferenceKind || 'preference', statement: args.statement, matterId }
|
|
261
|
-
: { matterId, debtor: 'user', creditor: args.creditor || 'someone', action: args.action, dueAt: args.dueAt, capability: 'none' }
|
|
506
|
+
? { kind: args.preferenceKind || 'preference', statement: args.statement, matterId: options.matterId }
|
|
507
|
+
: { matterId: options.matterId, debtor: 'user', creditor: args.creditor || 'someone', action: args.action, dueAt: args.dueAt, capability: 'none' }
|
|
262
508
|
if (args.kind === 'fact' && (!payload.predicate || !payload.object)) throw new Error('fact candidates require predicate and object')
|
|
263
509
|
if (args.kind === 'preference' && !payload.statement) throw new Error('preference candidates require statement')
|
|
264
510
|
if (args.kind === 'commitment' && !payload.action) throw new Error('commitment candidates require action')
|
|
265
|
-
const candidate = store.proposeCandidate({ kind: args.kind, payload, evidence: [{ quote: args.quote, turnId }] })
|
|
511
|
+
const candidate = options.store.proposeCandidate({ kind: args.kind, payload, evidence: [{ quote: args.quote, turnId: options.turnId }] })
|
|
266
512
|
return { ok: true, artifact: false, candidate: { id: candidate.id, kind: candidate.kind, status: candidate.status }, note: 'proposed; not active until accepted' }
|
|
267
513
|
}
|
|
268
514
|
if (name === 'search_memory') {
|
|
269
|
-
if (!ledger) throw new Error('search_memory requires a ledger')
|
|
270
|
-
return { ok: true, artifact: false, results: store?.searchMemory(args.query, { matterId }) ?? ledger.searchMemory(args.query, { matterId }) }
|
|
515
|
+
if (!options.ledger) throw new Error('search_memory requires a ledger')
|
|
516
|
+
return { ok: true, artifact: false, results: options.store?.searchMemory(args.query, { matterId: options.matterId }) ?? options.ledger.searchMemory(args.query, { matterId: options.matterId }) }
|
|
271
517
|
}
|
|
272
518
|
if (name === 'search_turns') {
|
|
273
|
-
const rows = store?.searchTurns(args.query, { limit: 6, matterId }) ?? []
|
|
519
|
+
const rows = options.store?.searchTurns(args.query, { limit: 6, matterId: options.matterId }) ?? []
|
|
274
520
|
return { ok: true, artifact: false, results: rows.map((r) => ({ seq: r.seq, role: r.role, content: r.content.slice(0, 300) })) }
|
|
275
521
|
}
|
|
276
522
|
if (name === 'routine_view') {
|
|
277
|
-
const routine = ledger?.listRoutines().find((r) => r.id === args.id && (r.status === 'active' || r.status === 'stale'))
|
|
278
|
-
if (!routine) throw new Error(
|
|
523
|
+
const routine = options.ledger?.listRoutines().find((r) => r.id === args.id && (r.status === 'active' || r.status === 'stale'))
|
|
524
|
+
if (!routine) throw new Error('unknown routine: ' + args.id)
|
|
279
525
|
return { ok: true, artifact: false, routine }
|
|
280
526
|
}
|
|
281
527
|
if (name === 'file_list') {
|
|
282
|
-
const path =
|
|
528
|
+
const path = policy.resolve(args.dir ?? '.', 'read')
|
|
283
529
|
const entries = await readdir(path, { withFileTypes: true })
|
|
284
|
-
return { ok: true, artifact: false, dir: path, entries: entries.slice(0, 200).map((e) =>
|
|
530
|
+
return { ok: true, artifact: false, dir: path, entries: entries.slice(0, 200).map((e) => (e.isDirectory() ? 'd ' : 'f ') + e.name) }
|
|
531
|
+
}
|
|
532
|
+
throw new Error('unknown tool: ' + name)
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
/**
|
|
536
|
+
* Execute one agent tool through the 0.2.3 file policy boundary. Every call
|
|
537
|
+
* is reported to onToolAction (allowed or denied) for the CLI audit chain.
|
|
538
|
+
*/
|
|
539
|
+
export async function executeTool(name, args = {}, options = {}) {
|
|
540
|
+
const toolArgs = args && typeof args === 'object' ? args : {}
|
|
541
|
+
const policy = createToolPolicy(options)
|
|
542
|
+
const spec = toolPathSpec(name, toolArgs)
|
|
543
|
+
let payload
|
|
544
|
+
try {
|
|
545
|
+
payload = await executeToolInner(name, toolArgs, policy, options)
|
|
546
|
+
} catch (error) {
|
|
547
|
+
await policy.audit({
|
|
548
|
+
tool: name,
|
|
549
|
+
action: spec ? spec.action : 'call',
|
|
550
|
+
input: spec ? spec.input : null,
|
|
551
|
+
allowed: false,
|
|
552
|
+
code: error && typeof error.code === 'string' ? error.code : 'TOOL_ERROR',
|
|
553
|
+
reason: error instanceof Error ? error.message : String(error),
|
|
554
|
+
})
|
|
555
|
+
throw error
|
|
285
556
|
}
|
|
286
|
-
|
|
557
|
+
const path = typeof payload?.path === 'string' ? payload.path : typeof payload?.dir === 'string' ? payload.dir : null
|
|
558
|
+
await policy.audit({
|
|
559
|
+
tool: name,
|
|
560
|
+
action: spec ? spec.action : 'call',
|
|
561
|
+
input: spec ? spec.input : null,
|
|
562
|
+
allowed: true,
|
|
563
|
+
code: 'OK',
|
|
564
|
+
reason: null,
|
|
565
|
+
path,
|
|
566
|
+
})
|
|
567
|
+
return payload
|
|
287
568
|
}
|
|
288
569
|
|
|
289
570
|
const SYSTEM = `You are a work secretary, not a chatbot.
|
|
@@ -295,7 +576,8 @@ Advisers is a local CLI: \`advisers\` starts the REPL, \`advisers chat "task"\`
|
|
|
295
576
|
- If the request is ambiguous and the answer would change the deliverable, ask one short question instead of guessing.
|
|
296
577
|
- Do not invent facts. Keep private matters private.
|
|
297
578
|
- Use memory_propose ONLY for a fact stated in the CURRENT user message. Never re-propose facts from earlier turns while answering a question; answer from the existing ledger/history. If an earlier fact is missing, say so plainly instead of trying to backfill it from old messages.
|
|
298
|
-
- If you promise to remind or follow up, call commitment_add first; never make an empty promise
|
|
579
|
+
- If you promise to remind or follow up, call commitment_add first; never make an empty promise.
|
|
580
|
+
${UNTRUSTED_DATA_RULES}`
|
|
299
581
|
|
|
300
582
|
function latestReminder(now = new Date()) {
|
|
301
583
|
const parts = new Intl.DateTimeFormat('zh-CN', { timeZone: 'Asia/Shanghai', year: 'numeric', month: '2-digit', day: '2-digit', weekday: 'long' }).formatToParts(now)
|
|
@@ -306,7 +588,7 @@ function latestReminder(now = new Date()) {
|
|
|
306
588
|
function fitMessages(messages, budget) {
|
|
307
589
|
const cap = Math.max(2000, Number(budget) || 12000)
|
|
308
590
|
const estimate = (list) => estimateTokens(list.map((m) => JSON.stringify(m)).join('\n')) + 1500
|
|
309
|
-
let fitted = messages.map((m, i) => (i > 0 && m.role === 'tool' && typeof m.content === 'string' && m.content.length > 4000 ? { ...m, content:
|
|
591
|
+
let fitted = messages.map((m, i) => (i > 0 && m.role === 'tool' && typeof m.content === 'string' && m.content.length > 4000 ? { ...m, content: truncateUntrusted(m.content, 4000) } : m))
|
|
310
592
|
while (estimate(fitted) > cap && fitted.length > 2) {
|
|
311
593
|
const start = fitted.findIndex((m, i) => i > 0 && m.role === 'user')
|
|
312
594
|
if (start < 0) break
|
|
@@ -342,6 +624,112 @@ async function callAgentModel(messages, options) {
|
|
|
342
624
|
}
|
|
343
625
|
|
|
344
626
|
|
|
627
|
+
const INJECTION_POLICY_ENV = 'ADVISERS_INJECTION_POLICY'
|
|
628
|
+
const INJECTION_POLICIES = new Set(['block', 'confirm', 'warn'])
|
|
629
|
+
// Untrusted text is scanned at most this much (head + tail) so a multi-MB
|
|
630
|
+
// file cannot stall the agent loop; the truncation is a scan-depth bound, not
|
|
631
|
+
// a trust promotion (the wrapped payload is still marked untrusted).
|
|
632
|
+
const UNTRUSTED_SCAN_CHARS = 100_000
|
|
633
|
+
const UNTRUSTED_SCAN_HEAD_CHARS = 60_000
|
|
634
|
+
const UNTRUSTED_SCAN_TAIL_CHARS = 40_000
|
|
635
|
+
|
|
636
|
+
function resolveInjectionPolicy(explicit, env = process.env) {
|
|
637
|
+
const raw = String(explicit == null ? (env?.[INJECTION_POLICY_ENV] ?? 'block') : explicit).trim().toLowerCase()
|
|
638
|
+
return INJECTION_POLICIES.has(raw) ? raw : 'block'
|
|
639
|
+
}
|
|
640
|
+
|
|
641
|
+
function boundedUntrustedScan(text) {
|
|
642
|
+
const raw = String(text == null ? '' : text)
|
|
643
|
+
if (raw.length <= UNTRUSTED_SCAN_CHARS) return raw
|
|
644
|
+
return raw.slice(0, UNTRUSTED_SCAN_HEAD_CHARS) + '\n[untrusted scan gap]\n' + raw.slice(-UNTRUSTED_SCAN_TAIL_CHARS)
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
function safetyWarningFrom(result, direction, source) {
|
|
648
|
+
if (!result || result.action === 'allow') return null
|
|
649
|
+
const injection = result.injection || null
|
|
650
|
+
return {
|
|
651
|
+
direction,
|
|
652
|
+
action: result.action,
|
|
653
|
+
code: result.code,
|
|
654
|
+
severity: result.severity || 'none',
|
|
655
|
+
confidence: typeof result.confidence === 'number' ? result.confidence : 0,
|
|
656
|
+
categories: Array.isArray(result.categories) ? [...result.categories] : [],
|
|
657
|
+
ruleIds: Array.isArray(result.ruleIds) ? [...result.ruleIds] : [],
|
|
658
|
+
surface: result.surface,
|
|
659
|
+
reason: injection && injection.reason ? injection.reason : result.code,
|
|
660
|
+
source: source || null,
|
|
661
|
+
crisis: Boolean(result.crisis),
|
|
662
|
+
evidenceHash: result.evidenceHash || null,
|
|
663
|
+
}
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
function assessUntrustedText(text, source, safetyKey) {
|
|
667
|
+
const result = classify(boundedUntrustedScan(text), { surface: 'agent.input', hmacKey: safetyKey })
|
|
668
|
+
const injection = result.injection || null
|
|
669
|
+
return {
|
|
670
|
+
result,
|
|
671
|
+
warning: safetyWarningFrom(result, 'untrusted', source),
|
|
672
|
+
highConfidence: Boolean(injection && injection.highConfidence),
|
|
673
|
+
severity: injection ? injection.severity : 'none',
|
|
674
|
+
ruleIds: injection && Array.isArray(injection.ruleIds) ? [...injection.ruleIds] : [],
|
|
675
|
+
reason: injection ? injection.reason : null,
|
|
676
|
+
source: source || null,
|
|
677
|
+
}
|
|
678
|
+
}
|
|
679
|
+
|
|
680
|
+
function normalizeUntrustedEntries(untrusted) {
|
|
681
|
+
const list = Array.isArray(untrusted) ? untrusted : (untrusted == null ? [] : [untrusted])
|
|
682
|
+
const entries = []
|
|
683
|
+
for (let index = 0; index < list.length; index += 1) {
|
|
684
|
+
const item = list[index]
|
|
685
|
+
if (item == null) continue
|
|
686
|
+
if (typeof item === 'string') {
|
|
687
|
+
if (item) entries.push({ label: 'untrusted:' + (index + 1), text: item })
|
|
688
|
+
continue
|
|
689
|
+
}
|
|
690
|
+
if (typeof item !== 'object') continue
|
|
691
|
+
const label = item.label || item.source || ('untrusted:' + (index + 1))
|
|
692
|
+
const body = item.text == null ? '' : String(item.text)
|
|
693
|
+
if (body) entries.push({ label: String(label), text: body })
|
|
694
|
+
}
|
|
695
|
+
return entries
|
|
696
|
+
}
|
|
697
|
+
|
|
698
|
+
async function evaluateInjectionGate({ policy, assessments, confirmInjection }) {
|
|
699
|
+
const risky = assessments.filter((assessment) => assessment.highConfidence)
|
|
700
|
+
if (!risky.length || policy === 'warn') return null
|
|
701
|
+
const primary = risky[0]
|
|
702
|
+
const record = {
|
|
703
|
+
code: 'UNTRUSTED_INJECTION',
|
|
704
|
+
severity: primary.severity || 'high',
|
|
705
|
+
ruleIds: [...primary.ruleIds],
|
|
706
|
+
source: primary.source || null,
|
|
707
|
+
reason: primary.reason || 'untrusted content contains instruction-like text',
|
|
708
|
+
}
|
|
709
|
+
if (policy !== 'confirm' || typeof confirmInjection !== 'function') return record
|
|
710
|
+
let allowed = false
|
|
711
|
+
try {
|
|
712
|
+
allowed = Boolean(await confirmInjection({ kind: 'untrusted-injection', ...record }))
|
|
713
|
+
} catch {
|
|
714
|
+
allowed = false
|
|
715
|
+
}
|
|
716
|
+
return allowed ? null : record
|
|
717
|
+
}
|
|
718
|
+
|
|
719
|
+
function blockedAgentResult({ record, warnings, artifacts, toolLog, steps, usage }) {
|
|
720
|
+
const ids = record.ruleIds.length ? record.ruleIds.join(',') : record.code
|
|
721
|
+
return {
|
|
722
|
+
reply: '已阻止:外部内容包含高风险提示注入(' + ids + '),该内容没有发送给模型。请先核实来源;如确需分析这段内容,可用 ADVISERS_INJECTION_POLICY=warn 重试。',
|
|
723
|
+
blocked: true,
|
|
724
|
+
blockReason: record,
|
|
725
|
+
safetyWarnings: warnings,
|
|
726
|
+
artifacts: [...new Set(artifacts)],
|
|
727
|
+
toolLog,
|
|
728
|
+
steps,
|
|
729
|
+
usage,
|
|
730
|
+
}
|
|
731
|
+
}
|
|
732
|
+
|
|
345
733
|
export async function runAgent({
|
|
346
734
|
runtime,
|
|
347
735
|
text,
|
|
@@ -350,10 +738,15 @@ export async function runAgent({
|
|
|
350
738
|
baseUrl,
|
|
351
739
|
model,
|
|
352
740
|
cwd = process.cwd(),
|
|
741
|
+
workspaceRoot,
|
|
742
|
+
allowPaths,
|
|
353
743
|
maxSteps = 8,
|
|
354
744
|
fetchImpl = fetch,
|
|
355
745
|
onTool,
|
|
746
|
+
onToolAction,
|
|
356
747
|
confirm,
|
|
748
|
+
confirmInjection,
|
|
749
|
+
injectionPolicy,
|
|
357
750
|
force = false,
|
|
358
751
|
backupDir,
|
|
359
752
|
store,
|
|
@@ -365,50 +758,106 @@ export async function runAgent({
|
|
|
365
758
|
thinking,
|
|
366
759
|
effort,
|
|
367
760
|
signal,
|
|
761
|
+
untrusted,
|
|
762
|
+
safetyKey,
|
|
368
763
|
}) {
|
|
369
|
-
|
|
764
|
+
// The 0.2.2 CLI appends attachments as raw <file> blocks; convert them to the
|
|
765
|
+
// untrusted-data boundary here so the source of the text is explicit even
|
|
766
|
+
// before the CLI migrates to the untrusted[] option.
|
|
767
|
+
const legacy = wrapLegacyAttachmentText(text)
|
|
768
|
+
const inputText = legacy.text
|
|
769
|
+
const userText = legacy.typedText
|
|
370
770
|
const policy = resolveThinking({ task: 'agent', explicit: effort })
|
|
371
771
|
const useThinking = thinking ?? policy.enabled
|
|
372
|
-
const
|
|
772
|
+
const gatePolicy = resolveInjectionPolicy(injectionPolicy)
|
|
773
|
+
const historyBlock = summary ? '\n\n<session-summary>\n' + summary + '\n</session-summary>' : ''
|
|
774
|
+
const warnings = []
|
|
775
|
+
const warningKeys = new Set()
|
|
776
|
+
const pushWarning = (warning) => {
|
|
777
|
+
if (!warning) return
|
|
778
|
+
const key = JSON.stringify([warning.direction, warning.action, warning.code, warning.source, warning.ruleIds])
|
|
779
|
+
if (warningKeys.has(key)) return
|
|
780
|
+
warningKeys.add(key)
|
|
781
|
+
warnings.push(warning)
|
|
782
|
+
}
|
|
783
|
+
// 1. classify untrusted input BEFORE it reaches the model, 2. wrap it so the
|
|
784
|
+
// model sees an explicit data boundary. Typed user text stays trusted; only
|
|
785
|
+
// wrapped blocks and the explicit untrusted[] option are scanned here.
|
|
786
|
+
const pendingAssessments = []
|
|
787
|
+
for (const block of untrustedBlocks(inputText)) {
|
|
788
|
+
pendingAssessments.push(assessUntrustedText(block.text, block.source || 'untrusted', safetyKey))
|
|
789
|
+
}
|
|
790
|
+
const untrustedEntries = normalizeUntrustedEntries(untrusted)
|
|
791
|
+
for (const entry of untrustedEntries) {
|
|
792
|
+
pendingAssessments.push(assessUntrustedText(entry.text, entry.label, safetyKey))
|
|
793
|
+
}
|
|
794
|
+
for (const assessment of pendingAssessments) pushWarning(assessment.warning)
|
|
795
|
+
const dataBlocks = untrustedEntries.map((entry) => wrapUntrusted(entry.label, entry.text)).join('\n\n')
|
|
796
|
+
const messageText = dataBlocks ? inputText + '\n\n' + dataBlocks : inputText
|
|
373
797
|
const messages = [
|
|
374
|
-
{ role: 'system', content:
|
|
798
|
+
{ role: 'system', content: SYSTEM + '\n\n' + context.prompt + historyBlock },
|
|
375
799
|
...history.filter((t) => t.role === (useThinking ? 'user' : t.role)).map((t) => ({ role: t.role, content: t.content })),
|
|
376
800
|
...(process.env.ADVISERS_LATEST_REMINDER === '0' ? [] : [{ role: 'latest_reminder', content: latestReminder() }]),
|
|
377
|
-
{ role: 'user', content:
|
|
801
|
+
{ role: 'user', content: messageText },
|
|
378
802
|
]
|
|
379
803
|
const artifacts = []
|
|
380
804
|
const toolLog = []
|
|
381
805
|
const usage = { promptTokens: 0, completionTokens: 0, reasoningTokens: 0, cachedTokens: 0, totalTokens: 0 }
|
|
382
806
|
for (let step = 0; step < maxSteps; step++) {
|
|
807
|
+
const blockReason = await evaluateInjectionGate({ policy: gatePolicy, assessments: pendingAssessments, confirmInjection })
|
|
808
|
+
pendingAssessments.length = 0
|
|
809
|
+
if (blockReason) return blockedAgentResult({ record: blockReason, warnings, artifacts, toolLog, steps: step, usage })
|
|
383
810
|
const startedAt = Date.now()
|
|
384
811
|
const result = await callAgentModel(fitMessages(messages, process.env.ADVISERS_CONTEXT_TOKENS), { apiKey, baseUrl, model, tools: LOCAL_TOOLS, fetchImpl, task: 'agent', thinking: useThinking, effort, signal })
|
|
385
812
|
if (result.usage) for (const key of Object.keys(usage)) usage[key] += Number(result.usage[key] || 0)
|
|
813
|
+
for (const warning of result.safetyWarnings || []) pushWarning(warning)
|
|
814
|
+
if (result.egressRedaction) {
|
|
815
|
+
pushWarning({
|
|
816
|
+
direction: 'input', action: 'redact', code: 'EGRESS_REDACTED', severity: 'medium', confidence: 1,
|
|
817
|
+
categories: ['pii'], ruleIds: [], surface: 'model.output', reason: '敏感串已在出站前脱敏', source: null,
|
|
818
|
+
crisis: false, evidenceHash: null, redactedCount: result.egressRedaction.count, redactedKinds: result.egressRedaction.kinds,
|
|
819
|
+
})
|
|
820
|
+
}
|
|
386
821
|
try { store?.addModelCall({ task: 'agent', model: result.model || model, effort: result.thinking?.effort, thinking: result.thinking?.enabled !== false, usage: result.usage, durationMs: Date.now() - startedAt, finishReason: result.finishReason, turnId }) } catch {}
|
|
387
|
-
if (!result.toolCalls.length)
|
|
822
|
+
if (!result.toolCalls.length) {
|
|
823
|
+
const done = { reply: result.content.trim(), artifacts: [...new Set(artifacts)], toolLog, steps: step + 1, usage, thinking: result.thinking }
|
|
824
|
+
if (warnings.length) done.safetyWarnings = warnings
|
|
825
|
+
return done
|
|
826
|
+
}
|
|
388
827
|
messages.push({ role: 'assistant', content: result.content, reasoning_content: result.reasoningContent, tool_calls: result.toolCalls })
|
|
389
828
|
for (const call of result.toolCalls) {
|
|
390
829
|
const name = call.function?.name
|
|
391
|
-
const id = call.id ??
|
|
830
|
+
const id = call.id ?? ('call_' + randomUUID())
|
|
392
831
|
let payload
|
|
393
832
|
try {
|
|
394
833
|
const args = JSON.parse(call.function?.arguments || '{}')
|
|
395
834
|
onTool?.(name, args)
|
|
396
|
-
const target = writeTarget(name, args, cwd)
|
|
835
|
+
const target = writeTarget(name, args, createToolPolicy({ cwd, workspaceRoot, allowPaths }))
|
|
397
836
|
if (target && !force && existsSync(target)) {
|
|
398
837
|
const allowed = confirm ? await confirm({ tool: name, path: target }) : false
|
|
399
838
|
if (!allowed) {
|
|
400
|
-
|
|
839
|
+
const declined = { reply: '未覆盖 ' + target + '。如需覆盖,请确认或设置 ADVISERS_FORCE=1。', artifacts: [...new Set(artifacts)], toolLog, declined: true, steps: step + 1 }
|
|
840
|
+
if (warnings.length) declined.safetyWarnings = warnings
|
|
841
|
+
return declined
|
|
401
842
|
}
|
|
402
843
|
}
|
|
403
|
-
payload = await executeTool(name, args, { cwd, ledger, backupDir, store, matterId, turnId, userText })
|
|
844
|
+
payload = await executeTool(name, args, { cwd, workspaceRoot, allowPaths, ledger, backupDir, store, matterId, turnId, userText, onToolAction })
|
|
404
845
|
if (payload.artifact && payload.path) artifacts.push(payload.path)
|
|
405
|
-
if (store && payload.artifact) { try { store.appendAudit({ actor: 'agent', action:
|
|
846
|
+
if (store && payload.artifact) { try { store.appendAudit({ actor: 'agent', action: 'tool.' + name, allowed: true, reason: payload.path }) } catch {} }
|
|
406
847
|
} catch (error) {
|
|
407
848
|
payload = { ok: false, error: error instanceof Error ? error.message : String(error) }
|
|
408
849
|
}
|
|
409
850
|
toolLog.push({ name, ok: payload.ok !== false, payload })
|
|
410
|
-
|
|
851
|
+
// 3. tool results are untrusted data: wrap + classify before the next
|
|
852
|
+
// model call so an injected result can never reach the model unwrapped.
|
|
853
|
+
const payloadText = JSON.stringify(payload)
|
|
854
|
+
const assessment = assessUntrustedText(payloadText, 'tool:' + name, safetyKey)
|
|
855
|
+
pushWarning(assessment.warning)
|
|
856
|
+
if (assessment.highConfidence) pendingAssessments.push(assessment)
|
|
857
|
+
messages.push({ role: 'tool', tool_call_id: id, content: wrapUntrusted('tool:' + name, payloadText) })
|
|
411
858
|
}
|
|
412
859
|
}
|
|
413
|
-
|
|
860
|
+
const final = { reply: '任务步骤超过上限,已停止;已完成的部分见文件。', artifacts: [...new Set(artifacts)], toolLog, steps: maxSteps, usage }
|
|
861
|
+
if (warnings.length) final.safetyWarnings = warnings
|
|
862
|
+
return final
|
|
414
863
|
}
|