advisers 0.1.0-preview.4 → 0.2.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.
Files changed (53) hide show
  1. package/LICENSE +131 -21
  2. package/NOTICE +34 -0
  3. package/README-zh.md +40 -9
  4. package/README.md +53 -10
  5. package/THIRD-PARTY-NOTICES.md +277 -0
  6. package/bin/advisers.js +4230 -122
  7. package/index.js +1 -1
  8. package/lib/agent.js +414 -0
  9. package/lib/attachments.js +283 -0
  10. package/lib/capture.js +168 -0
  11. package/lib/context-window.js +123 -0
  12. package/lib/digest.js +27 -0
  13. package/lib/doc-review.js +30 -0
  14. package/lib/egress.js +27 -0
  15. package/lib/evidence.js +1995 -0
  16. package/lib/ical.js +542 -0
  17. package/lib/imap.js +181 -0
  18. package/lib/importers.js +1001 -0
  19. package/lib/learning.js +46 -0
  20. package/lib/mcp-server.js +869 -0
  21. package/lib/model.js +307 -0
  22. package/lib/notify.js +189 -0
  23. package/lib/nudge.js +10 -0
  24. package/lib/ocr.js +47 -0
  25. package/lib/pdf.js +105 -0
  26. package/lib/pet-brief-store.js +51 -0
  27. package/lib/pet-brief.js +644 -0
  28. package/lib/receipt-verify.js +624 -0
  29. package/lib/relative-date.js +393 -0
  30. package/lib/remind.js +690 -0
  31. package/lib/research.js +193 -0
  32. package/lib/review.js +88 -0
  33. package/lib/routine.js +22 -0
  34. package/lib/safety/classifier.js +392 -0
  35. package/lib/safety/explain.js +157 -0
  36. package/lib/safety/index.js +333 -0
  37. package/lib/safety/redact.js +212 -0
  38. package/lib/safety/rules.js +824 -0
  39. package/lib/scheduler.js +399 -0
  40. package/lib/source.js +294 -0
  41. package/lib/sqlite.js +1022 -0
  42. package/lib/sync.js +129 -0
  43. package/lib/timestamp.js +45 -0
  44. package/lib/tos/index.js +332 -0
  45. package/lib/tos/manifest.json +32 -0
  46. package/lib/tos/privacy.zh-CN.md +136 -0
  47. package/lib/tos/safety.zh-CN.md +101 -0
  48. package/lib/tos/summary.zh-CN.md +12 -0
  49. package/lib/tos/terms.zh-CN.md +439 -0
  50. package/lib/ui.js +49 -0
  51. package/lib/undo.js +83 -0
  52. package/lib/vault.js +51 -0
  53. package/package.json +26 -4
package/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  export * from 'advisers-core'
2
2
 
3
- export const version = '0.1.0-preview.4'
3
+ export const version = '0.2.0'
4
4
  export const distribution = 'cordis'
5
5
  export const status = 'bootstrapping'
package/lib/agent.js ADDED
@@ -0,0 +1,414 @@
1
+ import { randomUUID } from 'node:crypto'
2
+ import { mkdir, readFile, readdir, writeFile } from 'node:fs/promises'
3
+ import { existsSync, lstatSync, realpathSync } from 'node:fs'
4
+ import { dirname, isAbsolute, relative, resolve } from 'node:path'
5
+ import { chatCompletion, ModelError, resolveThinking } from './model.js'
6
+ import { backupBeforeWrite } from './undo.js'
7
+ import { estimateTokens } from './context-window.js'
8
+
9
+ const OFFICE_KINDS = ['docx', 'xlsx', 'pptx', 'xmind', 'mermaid', 'drawio']
10
+ const TEMPLATE_NAMES = ['weekly', 'budget', 'presentation', 'flow', 'mindmap', 'minutes', 'notice']
11
+ const MAX_FILE_BYTES = 1_000_000
12
+
13
+ let officeModule
14
+
15
+ async function loadOffice() {
16
+ if (officeModule) return officeModule
17
+ try {
18
+ officeModule = await import('advisers-office')
19
+ } catch {
20
+ officeModule = await import('../../office/dist/index.js')
21
+ }
22
+ return officeModule
23
+ }
24
+
25
+ const DENY_SEGMENTS = new Set(['.git', '.hg', '.svn', '.dsh', '.github', 'node_modules'])
26
+ const DENY_FILES = new Set(['package.json', 'pnpm-lock.yaml', '.npmrc', 'soul.md', 'state.db', 'state.db-wal', 'state.db-shm'])
27
+
28
+ function safePath(cwd, input) {
29
+ const root = realpathSync(cwd)
30
+ const abs = resolve(root, input || '.')
31
+ const rel = relative(root, abs)
32
+ if (rel.startsWith('..') || isAbsolute(rel)) throw new Error(`path escapes workspace: ${input}`)
33
+ const parts = rel.split(/[\\/]+/).filter(Boolean)
34
+ for (const part of parts) {
35
+ const lower = part.toLowerCase()
36
+ if (DENY_SEGMENTS.has(lower) || DENY_FILES.has(lower)) throw new Error(`path is protected: ${part}`)
37
+ if (lower.startsWith('.env')) throw new Error(`path is protected: ${part}`)
38
+ }
39
+ let current = root
40
+ for (const part of parts.slice(0, -1)) {
41
+ current = resolve(current, part)
42
+ if (existsSync(current) && lstatSync(current).isSymbolicLink()) throw new Error(`symlink is not allowed: ${part}`)
43
+ }
44
+ if (existsSync(abs) && lstatSync(abs).isSymbolicLink()) throw new Error('symlink target is not allowed')
45
+ const parent = dirname(abs)
46
+ if (existsSync(parent)) {
47
+ const realParent = realpathSync(parent)
48
+ const parentRel = relative(root, realParent)
49
+ if (parentRel.startsWith('..') || isAbsolute(parentRel)) throw new Error('path escapes workspace through a symlink')
50
+ }
51
+ return abs
52
+ }
53
+
54
+ function tool(name, description, properties, required = []) {
55
+ return {
56
+ type: 'function',
57
+ function: {
58
+ name,
59
+ description,
60
+ parameters: { type: 'object', additionalProperties: false, properties, required },
61
+ },
62
+ }
63
+ }
64
+
65
+ export const LOCAL_TOOLS = [
66
+ tool('office_build', 'Build an Office/diagram artifact from a JSON spec. For xmind, spec must be {title,branches:[{label,children:string[]}]}; for mermaid/drawio, spec must be {kind:"flowchart",title,nodes:[{id,label}],edges:[{from,to,label?}]}.', {
67
+ kind: { type: 'string', enum: OFFICE_KINDS },
68
+ out: { type: 'string', description: 'Relative output path inside the workspace, e.g. out/q4.docx' },
69
+ spec: { type: 'object', description: 'Spec matching the chosen builder. docx:{title,sections}; xlsx:{columns,rows}; pptx:{title,slides}; xmind:{title,branches}; mermaid/drawio:{title,nodes,edges}.' },
70
+ }, ['kind', 'out', 'spec']),
71
+ tool('office_edit', 'Surgically edit an existing DOCX/XLSX/PPTX. Call office_read first. ops examples: {"op":"docx.setText","block":2,"text":"..."}; {"op":"xlsx.setCell","sheet":"预算","ref":"B2","value":200}; {"op":"pptx.setText","slide":1,"text":"..."}.', {
72
+ path: { type: 'string' },
73
+ out: { type: 'string' },
74
+ ops: { type: 'array', items: { type: 'object' } },
75
+ }, ['path', 'ops']),
76
+ tool('office_check', 'Run deterministic content checks on a DOCX/XLSX/PPTX (placeholders, formula errors, empty tables/sheets/slides). Does not judge correctness.', {
77
+ path: { type: 'string' },
78
+ }, ['path']),
79
+ tool('office_read', 'Read an existing DOCX/XLSX/PPTX and return structural text. Use before editing an existing file.', {
80
+ path: { type: 'string' },
81
+ max_chars: { type: 'number' },
82
+ }, ['path']),
83
+ tool('office_template', 'Build one of the secretary templates. data must match: weekly {period,done[],risks?,next?}; budget {rows:[{item,amount,owner?}]}; presentation {title,conclusion,bullets[]}; flow {title,steps[]}; mindmap {title,branches:[{label,children?}]}; minutes {date,agenda[],decisions?,actions?}; notice {title,issuer,recipients[],body[],signer,date}.', {
84
+ name: { type: 'string', enum: TEMPLATE_NAMES },
85
+ out: { type: 'string', description: 'Relative output path inside the workspace.' },
86
+ data: { type: 'object', description: 'Exact template input: weekly {period,done[],risks?,next?}; budget {rows:[{item,amount}]}; presentation {title,conclusion,bullets[]}; flow {title,steps[]}; mindmap {title,branches}.' },
87
+ }, ['name', 'out', 'data']),
88
+ tool('file_write', 'Write UTF-8 text to a file inside the workspace (max 1 MB).', {
89
+ path: { type: 'string' },
90
+ content: { type: 'string' },
91
+ }, ['path', 'content']),
92
+ tool('file_read', 'Read a UTF-8 text file inside the workspace (max 1 MB).', {
93
+ path: { type: 'string' },
94
+ }, ['path']),
95
+ tool('file_list', 'List files in a workspace directory.', {
96
+ dir: { type: 'string', description: 'Relative directory, default .' },
97
+ }, []),
98
+ tool('routine_view', 'Read one active routine by id. Use the routine index in context to choose.', {
99
+ id: { type: 'string' },
100
+ }, ['id']),
101
+ tool('commitment_add', 'Record a promise with its evidence. Use before saying you will remind/follow up.', {
102
+ action: { type: 'string' },
103
+ dueAt: { type: 'string', description: 'ISO timestamp or omit' },
104
+ creditor: { type: 'string' },
105
+ debtor: { type: 'string', enum: ['user', 'agent'] },
106
+ quote: { type: 'string', description: 'The exact user words that created the promise' },
107
+ }, ['action', 'quote']),
108
+ tool('memory_propose', 'Propose a memory candidate. The quote must be verbatim from the current user message. Nothing becomes active until the user accepts.', {
109
+ kind: { type: 'string', enum: ['fact', 'preference', 'commitment'] },
110
+ quote: { type: 'string' },
111
+ subject: { type: 'string' },
112
+ predicate: { type: 'string' },
113
+ object: { type: 'string' },
114
+ statement: { type: 'string' },
115
+ preferenceKind: { type: 'string' },
116
+ action: { type: 'string' },
117
+ creditor: { type: 'string' },
118
+ dueAt: { type: 'string' },
119
+ }, ['kind', 'quote']),
120
+ tool('search_memory', 'Search confirmed facts and preferences. Use before guessing what you already know.', {
121
+ query: { type: 'string' },
122
+ }, ['query']),
123
+ tool('search_turns', 'Search older conversation turns by keyword when the current window is insufficient.', {
124
+ query: { type: 'string' },
125
+ }, ['query']),
126
+ ]
127
+
128
+ function validateTemplate(name, data) {
129
+ if (!data || typeof data !== 'object') throw new Error(`${name} data must be an object`)
130
+ if (name === 'weekly' && (!data.period || !Array.isArray(data.done) || data.done.length === 0)) throw new Error('weekly data requires period and non-empty done[]')
131
+ if (name === 'budget' && (!Array.isArray(data.rows) || data.rows.length === 0)) throw new Error('budget data requires non-empty rows:[{item,amount}]')
132
+ if (name === 'presentation' && (!data.title || !data.conclusion || !Array.isArray(data.bullets))) throw new Error('presentation data requires title, conclusion, bullets[]')
133
+ if (name === 'flow' && (!data.title || !Array.isArray(data.steps) || data.steps.length === 0)) throw new Error('flow data requires title and non-empty steps[]')
134
+ if (name === 'mindmap' && (!data.title || !Array.isArray(data.branches) || data.branches.length === 0)) throw new Error('mindmap data requires title and non-empty branches[]')
135
+ if (name === 'minutes' && (!data.date || !Array.isArray(data.agenda) || data.agenda.length === 0)) throw new Error('minutes data requires date and non-empty agenda[]')
136
+ 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
+ }
138
+
139
+ async function runOfficeTool(name, args, cwd, backupDir) {
140
+ const office = await loadOffice()
141
+ const out = safePath(cwd, args.out)
142
+ await mkdir(dirname(out), { recursive: true })
143
+ let spec
144
+ if (name === 'office_build') {
145
+ if (!OFFICE_KINDS.includes(args.kind)) throw new Error(`unsupported kind: ${args.kind}`)
146
+ spec = args.spec
147
+ if (args.kind === 'xmind' && (!Array.isArray(spec?.branches) || spec.branches.length === 0)) {
148
+ throw new Error('xmind spec requires a non-empty branches array: [{label, children: string[]}]')
149
+ }
150
+ if (args.kind === 'xlsx' && (!Array.isArray(spec?.columns) || !Array.isArray(spec?.rows) || spec.rows.length === 0)) {
151
+ throw new Error('xlsx spec requires non-empty columns[] and rows[]')
152
+ }
153
+ if (args.kind === 'docx' && (!spec?.title || !Array.isArray(spec?.sections))) {
154
+ throw new Error('docx spec requires title and sections[]')
155
+ }
156
+ if (args.kind === 'pptx' && (!spec?.title || !Array.isArray(spec?.slides))) {
157
+ throw new Error('pptx spec requires title and slides[]')
158
+ }
159
+ if ((args.kind === 'mermaid' || args.kind === 'drawio') && (!Array.isArray(spec?.nodes) || spec.nodes.length === 0)) {
160
+ throw new Error('diagram spec requires nodes: [{id,label}]')
161
+ }
162
+ } else {
163
+ if (!TEMPLATE_NAMES.includes(args.name)) throw new Error(`unsupported template: ${args.name}`)
164
+ validateTemplate(args.name, args.data)
165
+ spec = args.name === 'weekly' ? office.weeklyReport(args.data)
166
+ : args.name === 'budget' ? office.budget(args.data)
167
+ : args.name === 'presentation' ? office.presentation(args.data)
168
+ : args.name === 'flow' ? office.flow(args.data)
169
+ : args.name === 'minutes' ? office.meetingMinutes(args.data)
170
+ : args.name === 'notice' ? office.notice(args.data)
171
+ : office.mindmap(args.data)
172
+ }
173
+ let buffer
174
+ let result
175
+ const kind = name === 'office_build' ? args.kind : (args.name === 'budget' ? 'xlsx' : args.name === 'presentation' ? 'pptx' : (args.name === 'flow' || args.name === 'mindmap') ? 'mermaid' : 'docx')
176
+ if (kind === 'docx') { buffer = await office.buildDocx(spec); result = await office.validateOffice(buffer, 'docx') }
177
+ else if (kind === 'xlsx') { buffer = await office.buildXlsx(spec); result = await office.validateOffice(buffer, 'xlsx') }
178
+ else if (kind === 'pptx') { buffer = await office.buildPptx(spec); result = await office.validateOffice(buffer, 'pptx') }
179
+ else if (kind === 'xmind') { buffer = await office.buildXmind(spec); result = await office.validateXmind(buffer) }
180
+ else if (kind === 'drawio') { buffer = Buffer.from(office.buildDrawio(spec)); result = { ok: true, missing: [] } }
181
+ else { buffer = Buffer.from(office.buildMermaid(spec)); result = { ok: true, missing: [] } }
182
+ await backupBeforeWrite(out, { cwd, backupDir })
183
+ await writeFile(out, buffer)
184
+ return { ok: result.ok, artifact: true, path: out, bytes: buffer.length, missing: result.missing ?? [] }
185
+ }
186
+
187
+ function writeTarget(name, args, cwd) {
188
+ try {
189
+ if (name === 'office_build' || name === 'office_template') return safePath(cwd, args.out)
190
+ if (name === 'office_edit') return safePath(cwd, args.out || args.path)
191
+ if (name === 'file_write') return safePath(cwd, args.path)
192
+ } catch {
193
+ return null
194
+ }
195
+ return null
196
+ }
197
+
198
+ export async function executeTool(name, args, { cwd = process.cwd(), ledger, backupDir, store, matterId, turnId, userText } = {}) {
199
+ if (name === 'office_build' || name === 'office_template') return runOfficeTool(name, args, cwd, backupDir)
200
+ if (name === 'file_write') {
201
+ if (typeof args.content !== 'string' || Buffer.byteLength(args.content) > MAX_FILE_BYTES) throw new Error('content is missing or too large')
202
+ const path = safePath(cwd, args.path)
203
+ await mkdir(dirname(path), { recursive: true })
204
+ await backupBeforeWrite(path, { cwd, backupDir })
205
+ await writeFile(path, args.content)
206
+ return { ok: true, artifact: true, path, bytes: Buffer.byteLength(args.content) }
207
+ }
208
+ if (name === 'file_read') {
209
+ const path = safePath(cwd, args.path)
210
+ const content = await readFile(path, 'utf8')
211
+ if (Buffer.byteLength(content) > MAX_FILE_BYTES) throw new Error('file is too large')
212
+ return { ok: true, artifact: false, path, content }
213
+ }
214
+ if (name === 'office_edit') {
215
+ const source = safePath(cwd, args.path)
216
+ const target = safePath(cwd, args.out || args.path)
217
+ const office = await loadOffice()
218
+ const ext = source.split('.').pop()?.toLowerCase()
219
+ if (!['docx', 'xlsx', 'pptx'].includes(ext)) throw new Error('office_edit supports docx/xlsx/pptx')
220
+ const result = await office.editOffice(await readFile(source), ext, args.ops)
221
+ if (!result.ok) throw new Error(result.error || 'edit failed')
222
+ await mkdir(dirname(target), { recursive: true })
223
+ await backupBeforeWrite(target, { cwd, backupDir })
224
+ await writeFile(target, result.buffer)
225
+ return { ok: true, artifact: true, path: target, bytes: result.buffer.length, changes: result.changes }
226
+ }
227
+ if (name === 'office_check') {
228
+ const office = await loadOffice()
229
+ const target = safePath(cwd, args.path)
230
+ const kind = String(args.path).split('.').pop()?.toLowerCase()
231
+ if (!['docx', 'xlsx', 'pptx'].includes(kind)) throw new Error('office_check supports docx/xlsx/pptx')
232
+ return { ok: true, artifact: false, result: await office.checkOffice(await readFile(target), kind) }
233
+ }
234
+ if (name === 'office_read') {
235
+ const target = safePath(cwd, args.path)
236
+ const office = await loadOffice()
237
+ const doc = await office.readOffice(await readFile(target))
238
+ const text = office.officeToText(doc, Math.min(Number(args.max_chars) || 20_000, 50_000))
239
+ return { ok: true, artifact: false, kind: doc.kind, text }
240
+ }
241
+ 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,
245
+ debtor: args.debtor === 'agent' ? 'agent' : 'user',
246
+ creditor: args.creditor || /(?:发给|给|向|对)([\u4e00-\u9fa5A-Za-z0-9_]{1,12})/.exec(args.action)?.[1] || 'someone',
247
+ action: args.action,
248
+ dueAt: args.dueAt,
249
+ capability: 'todo',
250
+ evidence: [{ sessionId: turnId || 'local', turnId: turnId || 'local', quote: args.quote }],
251
+ })
252
+ return { ok: true, artifact: false, commitment }
253
+ }
254
+ 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')
257
+ const payload = args.kind === 'fact'
258
+ ? { subject: args.subject || 'user', predicate: args.predicate, object: args.object, matterId }
259
+ : 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' }
262
+ if (args.kind === 'fact' && (!payload.predicate || !payload.object)) throw new Error('fact candidates require predicate and object')
263
+ if (args.kind === 'preference' && !payload.statement) throw new Error('preference candidates require statement')
264
+ 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 }] })
266
+ return { ok: true, artifact: false, candidate: { id: candidate.id, kind: candidate.kind, status: candidate.status }, note: 'proposed; not active until accepted' }
267
+ }
268
+ 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 }) }
271
+ }
272
+ if (name === 'search_turns') {
273
+ const rows = store?.searchTurns(args.query, { limit: 6, matterId }) ?? []
274
+ return { ok: true, artifact: false, results: rows.map((r) => ({ seq: r.seq, role: r.role, content: r.content.slice(0, 300) })) }
275
+ }
276
+ 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(`unknown routine: ${args.id}`)
279
+ return { ok: true, artifact: false, routine }
280
+ }
281
+ if (name === 'file_list') {
282
+ const path = safePath(cwd, args.dir ?? '.')
283
+ const entries = await readdir(path, { withFileTypes: true })
284
+ return { ok: true, artifact: false, dir: path, entries: entries.slice(0, 200).map((e) => `${e.isDirectory() ? 'd' : 'f'} ${e.name}`) }
285
+ }
286
+ throw new Error(`unknown tool: ${name}`)
287
+ }
288
+
289
+ const SYSTEM = `You are a work secretary, not a chatbot.
290
+ Advisers is a local CLI: \`advisers\` starts the REPL, \`advisers chat "task"\` runs one task, \`advisers status\` shows state, \`advisers office\`/\`advisers template\` build files. It is NOT a directory of consultants; never invent product features.
291
+ - Reply in the user's language, BLUF, no filler.
292
+ - Use tools to create files only when the user asks for a document/file or the task clearly needs one; otherwise answer in chat. Never claim a file exists unless the tool succeeded.
293
+ - For Office work, choose the right builder/template, put deliverables under out/ unless the user says otherwise.
294
+ - For Office deliverables, read the file back with office_read and run office_check before claiming completion; report blockers instead of saying done.
295
+ - If the request is ambiguous and the answer would change the deliverable, ask one short question instead of guessing.
296
+ - Do not invent facts. Keep private matters private.
297
+ - 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.`
299
+
300
+ function latestReminder(now = new Date()) {
301
+ const parts = new Intl.DateTimeFormat('zh-CN', { timeZone: 'Asia/Shanghai', year: 'numeric', month: '2-digit', day: '2-digit', weekday: 'long' }).formatToParts(now)
302
+ const get = (type) => parts.find((p) => p.type === type)?.value ?? ''
303
+ return `${get('year')}-${get('month')}-${get('day')},${get('weekday')},${process.env.ADVISERS_LOCATION || ''},App,中文`
304
+ }
305
+
306
+ function fitMessages(messages, budget) {
307
+ const cap = Math.max(2000, Number(budget) || 12000)
308
+ 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: `${m.content.slice(0, 4000)}\n[tool output truncated]` } : m))
310
+ while (estimate(fitted) > cap && fitted.length > 2) {
311
+ const start = fitted.findIndex((m, i) => i > 0 && m.role === 'user')
312
+ if (start < 0) break
313
+ let end = start + 1
314
+ while (end < fitted.length && fitted[end].role !== 'user') end++
315
+ if (end >= fitted.length) break
316
+ fitted = [...fitted.slice(0, start), ...fitted.slice(end)]
317
+ }
318
+ if (estimate(fitted) > cap) fitted[0] = { ...fitted[0], content: `${String(fitted[0].content).slice(0, cap * 3)}\n[context truncated to budget]` }
319
+ return fitted
320
+ }
321
+
322
+ function stripReasoning(messages) {
323
+ return messages.map((m) => { const copy = { ...m }; delete copy.reasoning_content; return copy })
324
+ }
325
+
326
+ async function callAgentModel(messages, options) {
327
+ try {
328
+ return await chatCompletion({ ...options, messages })
329
+ } catch (error) {
330
+ const body = String(error?.body || '')
331
+ if (error?.status === 400 && /reasoning_content/i.test(body)) {
332
+ const withEmpty = messages.map((m) => m.role === 'assistant' ? { ...m, reasoning_content: m.reasoning_content ?? '' } : m)
333
+ try { return await chatCompletion({ ...options, messages: withEmpty }) } catch (second) {
334
+ if (second?.status === 400 && /reasoning_content/i.test(String(second.body || ''))) {
335
+ return chatCompletion({ ...options, messages: stripReasoning(messages), thinking: false })
336
+ }
337
+ throw second
338
+ }
339
+ }
340
+ throw error
341
+ }
342
+ }
343
+
344
+
345
+ export async function runAgent({
346
+ runtime,
347
+ text,
348
+ context,
349
+ apiKey,
350
+ baseUrl,
351
+ model,
352
+ cwd = process.cwd(),
353
+ maxSteps = 8,
354
+ fetchImpl = fetch,
355
+ onTool,
356
+ confirm,
357
+ force = false,
358
+ backupDir,
359
+ store,
360
+ matterId,
361
+ turnId,
362
+ history = [],
363
+ summary = '',
364
+ ledger,
365
+ thinking,
366
+ effort,
367
+ signal,
368
+ }) {
369
+ const userText = text
370
+ const policy = resolveThinking({ task: 'agent', explicit: effort })
371
+ const useThinking = thinking ?? policy.enabled
372
+ const historyBlock = summary ? `\n\n<session-summary>\n${summary}\n</session-summary>` : ''
373
+ const messages = [
374
+ { role: 'system', content: `${SYSTEM}\n\n${context.prompt}${historyBlock}` },
375
+ ...history.filter((t) => t.role === (useThinking ? 'user' : t.role)).map((t) => ({ role: t.role, content: t.content })),
376
+ ...(process.env.ADVISERS_LATEST_REMINDER === '0' ? [] : [{ role: 'latest_reminder', content: latestReminder() }]),
377
+ { role: 'user', content: text },
378
+ ]
379
+ const artifacts = []
380
+ const toolLog = []
381
+ const usage = { promptTokens: 0, completionTokens: 0, reasoningTokens: 0, cachedTokens: 0, totalTokens: 0 }
382
+ for (let step = 0; step < maxSteps; step++) {
383
+ const startedAt = Date.now()
384
+ 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
+ if (result.usage) for (const key of Object.keys(usage)) usage[key] += Number(result.usage[key] || 0)
386
+ 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) return { reply: result.content.trim(), artifacts: [...new Set(artifacts)], toolLog, steps: step + 1, usage, thinking: result.thinking }
388
+ messages.push({ role: 'assistant', content: result.content, reasoning_content: result.reasoningContent, tool_calls: result.toolCalls })
389
+ for (const call of result.toolCalls) {
390
+ const name = call.function?.name
391
+ const id = call.id ?? `call_${randomUUID()}`
392
+ let payload
393
+ try {
394
+ const args = JSON.parse(call.function?.arguments || '{}')
395
+ onTool?.(name, args)
396
+ const target = writeTarget(name, args, cwd)
397
+ if (target && !force && existsSync(target)) {
398
+ const allowed = confirm ? await confirm({ tool: name, path: target }) : false
399
+ if (!allowed) {
400
+ return { reply: `未覆盖 ${target}。如需覆盖,请确认或设置 ADVISERS_FORCE=1。`, artifacts: [...new Set(artifacts)], toolLog, declined: true, steps: step + 1 }
401
+ }
402
+ }
403
+ payload = await executeTool(name, args, { cwd, ledger, backupDir, store, matterId, turnId, userText })
404
+ if (payload.artifact && payload.path) artifacts.push(payload.path)
405
+ if (store && payload.artifact) { try { store.appendAudit({ actor: 'agent', action: `tool.${name}`, allowed: true, reason: payload.path }) } catch {} }
406
+ } catch (error) {
407
+ payload = { ok: false, error: error instanceof Error ? error.message : String(error) }
408
+ }
409
+ toolLog.push({ name, ok: payload.ok !== false, payload })
410
+ messages.push({ role: 'tool', tool_call_id: id, content: JSON.stringify(payload) })
411
+ }
412
+ }
413
+ return { reply: '任务步骤超过上限,已停止;已完成的部分见文件。', artifacts: [...new Set(artifacts)], toolLog, steps: maxSteps, usage }
414
+ }