@xiangyixie/dsh-superagent 0.14.7 → 0.14.9
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/CHANGELOG.md +31 -0
- package/README.en.md +4 -4
- package/README.md +4 -4
- package/README.zh.md +4 -4
- package/lib/console.js +383 -9
- package/lib/index.js +266 -0
- package/lib/workbench.js +11 -2
- package/package.json +1 -1
- package/public/console.html +970 -65
package/lib/console.js
CHANGED
|
@@ -14,6 +14,7 @@ import { readFileSync } from 'node:fs'
|
|
|
14
14
|
import fsp from 'node:fs/promises'
|
|
15
15
|
import { createServer } from 'node:http'
|
|
16
16
|
import path from 'node:path'
|
|
17
|
+
import { isInside } from './memory.js'
|
|
17
18
|
import {
|
|
18
19
|
errorPayload,
|
|
19
20
|
readJson,
|
|
@@ -47,6 +48,28 @@ const REQUEST_TIMEOUT_MS = 30_000
|
|
|
47
48
|
const APPROVAL_TIMEOUT_MS = 10 * 60 * 1000
|
|
48
49
|
const ROUTE_HINT = 'GET / serves the console; the JSON API is under /api/console.'
|
|
49
50
|
const MAX_ARTIFACT_BYTES = 2 * 1024 * 1024
|
|
51
|
+
// A file dropped on the composer is copied into the conversation's own
|
|
52
|
+
// workspace. The cap is generous for a screenshot or a deck, small enough that
|
|
53
|
+
// a stray folder cannot fill the disk through the page.
|
|
54
|
+
const MAX_UPLOAD_BYTES = 8 * 1024 * 1024
|
|
55
|
+
// base64 inflates the payload by about a third; the JSON wrapper needs a little
|
|
56
|
+
// more room than the decoded file itself.
|
|
57
|
+
const UPLOAD_BODY_LIMIT = 12 * 1024 * 1024
|
|
58
|
+
const UPLOAD_DIR = '.superagent/uploads'
|
|
59
|
+
const UPLOAD_TYPES = new Set([
|
|
60
|
+
'.png', '.jpg', '.jpeg', '.gif', '.webp', '.svg', '.bmp',
|
|
61
|
+
'.pdf', '.md', '.markdown', '.txt', '.log', '.csv', '.tsv', '.json', '.yml', '.yaml', '.xml',
|
|
62
|
+
'.doc', '.docx', '.xls', '.xlsx', '.ppt', '.pptx', '.rtf',
|
|
63
|
+
'.zip', '.tar', '.gz', '.7z',
|
|
64
|
+
'.js', '.mjs', '.cjs', '.ts', '.tsx', '.jsx', '.py', '.css', '.html', '.htm', '.sql', '.sh',
|
|
65
|
+
'.ps1', '.toml', '.ini', '.ipynb',
|
|
66
|
+
])
|
|
67
|
+
const UPLOAD_TYPES_TEXT = '图片、PDF、Markdown/文本、CSV/JSON、Office 文档、压缩包或代码文件'
|
|
68
|
+
// Which notices a person already read. The notices themselves are derived from
|
|
69
|
+
// durable runs on every load, so reopening the page after a run finished shows
|
|
70
|
+
// "跑完了" without this file having to hold a second copy of the run history.
|
|
71
|
+
const NOTICE_FILE = 'console-notices.json'
|
|
72
|
+
const MAX_READ_NOTICES = 200
|
|
50
73
|
|
|
51
74
|
/** Types the console may preview inline; anything else is refused, not sniffed. */
|
|
52
75
|
const ARTIFACT_TYPES = new Map([
|
|
@@ -147,19 +170,36 @@ function boundedSnapshot(frame) {
|
|
|
147
170
|
* @param {object} options.host - host adapter; see README.
|
|
148
171
|
* @param {string} options.version - plugin version reported by `/api/health`.
|
|
149
172
|
* @param {(message: string) => void} [options.log] - diagnostics sink.
|
|
173
|
+
* @param {number} [options.maxUploadBytes] - per-file cap for dropped files.
|
|
150
174
|
*/
|
|
151
|
-
export function createConsole({
|
|
175
|
+
export function createConsole({
|
|
176
|
+
port,
|
|
177
|
+
stateRoot,
|
|
178
|
+
host,
|
|
179
|
+
version,
|
|
180
|
+
log = () => {},
|
|
181
|
+
maxUploadBytes = MAX_UPLOAD_BYTES,
|
|
182
|
+
}) {
|
|
152
183
|
if (!host || typeof host !== 'object') throw new Error('createConsole needs a host adapter')
|
|
153
184
|
const token = randomBytes(32).toString('base64url')
|
|
154
185
|
const instanceId = randomBytes(6).toString('hex')
|
|
155
186
|
const discoveryPath = path.join(stateRoot, DISCOVERY_FILE)
|
|
156
187
|
const timelinePath = path.join(stateRoot, TIMELINE_FILE)
|
|
188
|
+
const noticePath = path.join(stateRoot, NOTICE_FILE)
|
|
189
|
+
const uploadLimit = Number.isFinite(maxUploadBytes) && maxUploadBytes > 0
|
|
190
|
+
? Math.floor(maxUploadBytes)
|
|
191
|
+
: MAX_UPLOAD_BYTES
|
|
192
|
+
const noticeRead = new Set()
|
|
157
193
|
const startedAt = new Date().toISOString()
|
|
158
194
|
const clients = new Set()
|
|
159
195
|
// Approval questions raised inside this conversation wait here until the open
|
|
160
196
|
// page answers them. Nothing resolves on its own: a page that never answers
|
|
161
197
|
// fails closed to `cancelled`, and no path grants a call without a decision.
|
|
162
198
|
const approvals = new Map()
|
|
199
|
+
// Tools the person chose to let through for the rest of this conversation.
|
|
200
|
+
// The host only grants one call at a time, so this list is the console's own
|
|
201
|
+
// scope, cleared whenever the conversation changes.
|
|
202
|
+
const sessionAllowedTools = new Set()
|
|
163
203
|
let boundPort = null
|
|
164
204
|
let server = null
|
|
165
205
|
let page = null
|
|
@@ -206,6 +246,7 @@ export function createConsole({ port, stateRoot, host, version, log = () => {} }
|
|
|
206
246
|
|| timeline.records.length > TIMELINE_MAX_RECORDS
|
|
207
247
|
|| timeline.records.reduce((sum, record) => sum + Buffer.byteLength(JSON.stringify(record)), 0) > TIMELINE_MAX_BYTES
|
|
208
248
|
}
|
|
249
|
+
loadNoticeRead()
|
|
209
250
|
|
|
210
251
|
const url = () => `http://127.0.0.1:${boundPort}`
|
|
211
252
|
const allowedHosts = () => new Set([
|
|
@@ -302,12 +343,13 @@ export function createConsole({ port, stateRoot, host, version, log = () => {} }
|
|
|
302
343
|
* the whole fix; a real filesystem error still surfaces to the caller.
|
|
303
344
|
*
|
|
304
345
|
* @param {string} tmp - fully written temporary file beside the target.
|
|
346
|
+
* @param {string} [target] - destination; the timeline file by default.
|
|
305
347
|
* @returns {Promise<void>} resolves once the target holds the new bytes.
|
|
306
348
|
*/
|
|
307
|
-
async function replaceTimeline(tmp) {
|
|
349
|
+
async function replaceTimeline(tmp, target = timelinePath) {
|
|
308
350
|
for (let attempt = 0; ; attempt += 1) {
|
|
309
351
|
try {
|
|
310
|
-
await fsp.rename(tmp,
|
|
352
|
+
await fsp.rename(tmp, target)
|
|
311
353
|
return
|
|
312
354
|
} catch (error) {
|
|
313
355
|
const transient = error?.code === 'EPERM' || error?.code === 'EACCES' || error?.code === 'EBUSY'
|
|
@@ -317,6 +359,38 @@ export function createConsole({ port, stateRoot, host, version, log = () => {} }
|
|
|
317
359
|
}
|
|
318
360
|
}
|
|
319
361
|
|
|
362
|
+
/** Remembered notice ids, so a badge does not come back after a reload. */
|
|
363
|
+
function loadNoticeRead() {
|
|
364
|
+
try {
|
|
365
|
+
const parsed = JSON.parse(readFileSync(noticePath, 'utf8'))
|
|
366
|
+
for (const id of Array.isArray(parsed?.read) ? parsed.read : []) {
|
|
367
|
+
if (typeof id === 'string' && id.trim()) noticeRead.add(id.trim())
|
|
368
|
+
}
|
|
369
|
+
} catch (error) {
|
|
370
|
+
if (error?.code !== 'ENOENT') log(`console: cannot read ${noticePath}: ${messageOf(error)}`)
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
/**
|
|
375
|
+
* Persist the read set. It is bounded, so a console used for months cannot
|
|
376
|
+
* grow the file without limit; the oldest ids fall off first.
|
|
377
|
+
*
|
|
378
|
+
* @returns {Promise<void>} resolves once the file is replaced (or the failure logged).
|
|
379
|
+
*/
|
|
380
|
+
async function saveNoticeRead() {
|
|
381
|
+
const ids = [...noticeRead].slice(-MAX_READ_NOTICES)
|
|
382
|
+
noticeRead.clear()
|
|
383
|
+
for (const id of ids) noticeRead.add(id)
|
|
384
|
+
const tmp = `${noticePath}.${process.pid}.tmp`
|
|
385
|
+
try {
|
|
386
|
+
await fsp.mkdir(path.dirname(noticePath), { recursive: true })
|
|
387
|
+
await fsp.writeFile(tmp, `${JSON.stringify({ version: 1, read: ids })}\n`, 'utf8')
|
|
388
|
+
await replaceTimeline(tmp, noticePath)
|
|
389
|
+
} catch (error) {
|
|
390
|
+
log(`console: cannot save ${noticePath}: ${messageOf(error)}`)
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
|
|
320
394
|
function authorize(req, { allowQuery = false } = {}) {
|
|
321
395
|
if (!boundPort) {
|
|
322
396
|
throw new WorkbenchError(503, 'the console is not listening yet', { id: 'not-ready' })
|
|
@@ -394,10 +468,16 @@ export function createConsole({ port, stateRoot, host, version, log = () => {} }
|
|
|
394
468
|
*/
|
|
395
469
|
function askApproval(request = {}) {
|
|
396
470
|
if (clients.size === 0) return Promise.resolve('cancelled')
|
|
471
|
+
const toolName = typeof request.toolName === 'string' && request.toolName ? request.toolName : 'tool'
|
|
472
|
+
if (sessionAllowedTools.has(toolName)) {
|
|
473
|
+
broadcast({ type: 'approval', action: 'auto', toolName })
|
|
474
|
+
return Promise.resolve('allowed-once')
|
|
475
|
+
}
|
|
397
476
|
const id = `ap_${randomBytes(6).toString('hex')}`
|
|
477
|
+
const askedAt = Date.now()
|
|
398
478
|
const payload = {
|
|
399
479
|
id,
|
|
400
|
-
toolName
|
|
480
|
+
toolName,
|
|
401
481
|
callId: request.callId ?? null,
|
|
402
482
|
callArguments: typeof request.callArguments === 'string' ? request.callArguments.slice(0, 4000) : null,
|
|
403
483
|
reason: typeof request.reason === 'string' ? request.reason : null,
|
|
@@ -406,7 +486,8 @@ export function createConsole({ port, stateRoot, host, version, log = () => {} }
|
|
|
406
486
|
: null,
|
|
407
487
|
agentId: request.agentId ?? null,
|
|
408
488
|
source: request.source ?? null,
|
|
409
|
-
askedAt: new Date().toISOString(),
|
|
489
|
+
askedAt: new Date(askedAt).toISOString(),
|
|
490
|
+
expiresAt: new Date(askedAt + APPROVAL_TIMEOUT_MS).toISOString(),
|
|
410
491
|
}
|
|
411
492
|
return new Promise(resolve => {
|
|
412
493
|
const settle = outcome => {
|
|
@@ -589,6 +670,7 @@ export function createConsole({ port, stateRoot, host, version, log = () => {} }
|
|
|
589
670
|
throw new WorkbenchError(502, 'the host created a session but returned no id', { id: 'session-create-failed' })
|
|
590
671
|
}
|
|
591
672
|
if (currentSessionId !== sessionId) {
|
|
673
|
+
sessionAllowedTools.clear()
|
|
592
674
|
detach()
|
|
593
675
|
currentSessionId = sessionId
|
|
594
676
|
resetStore(sessionId)
|
|
@@ -604,6 +686,45 @@ export function createConsole({ port, stateRoot, host, version, log = () => {} }
|
|
|
604
686
|
return { sessionId, capabilities: caps }
|
|
605
687
|
}
|
|
606
688
|
|
|
689
|
+
/**
|
|
690
|
+
* Show a conversation the host already has. The page reloads afterwards, so
|
|
691
|
+
* it re-runs bootstrap and replays that session through the normal path
|
|
692
|
+
* instead of the console inventing a second rendering pipeline.
|
|
693
|
+
*
|
|
694
|
+
* @param {string} sessionId - a conversation this console created.
|
|
695
|
+
*/
|
|
696
|
+
async function switchSession(sessionId) {
|
|
697
|
+
const caps = capabilities()
|
|
698
|
+
if (!caps.chat) {
|
|
699
|
+
throw new WorkbenchError(503, caps.reason ?? 'the host exposes no conversation session API', {
|
|
700
|
+
id: 'console-unavailable',
|
|
701
|
+
})
|
|
702
|
+
}
|
|
703
|
+
if (typeof host.openSession !== 'function') {
|
|
704
|
+
throw new WorkbenchError(501, 'this host cannot reopen a conversation', { id: 'switch-unavailable' })
|
|
705
|
+
}
|
|
706
|
+
const target = await host.openSession(sessionId)
|
|
707
|
+
if (!target) {
|
|
708
|
+
throw new WorkbenchError(404, 'no such conversation in this console space', {
|
|
709
|
+
id: 'unknown-session',
|
|
710
|
+
hint: 'the history list only contains conversations this console created.',
|
|
711
|
+
})
|
|
712
|
+
}
|
|
713
|
+
if (target.sessionId === currentSessionId) {
|
|
714
|
+
return { sessionId: target.sessionId, capabilities: caps, switched: false }
|
|
715
|
+
}
|
|
716
|
+
currentSessionId = target.sessionId
|
|
717
|
+
rememberedSessionId = target.sessionId
|
|
718
|
+
sessionAllowedTools.clear()
|
|
719
|
+
detach()
|
|
720
|
+
resetStore(target.sessionId)
|
|
721
|
+
await saveTimeline(true)
|
|
722
|
+
broadcast({ type: 'session', sessionId: target.sessionId, mode: 'chat', switched: true })
|
|
723
|
+
if (clients.size > 0) attach(target.sessionId)
|
|
724
|
+
refreshRuns({ force: true }).catch(() => {})
|
|
725
|
+
return { sessionId: target.sessionId, capabilities: caps }
|
|
726
|
+
}
|
|
727
|
+
|
|
607
728
|
async function ensureSession() {
|
|
608
729
|
if (currentSessionId) return { sessionId: currentSessionId, capabilities: capabilities() }
|
|
609
730
|
return createSession()
|
|
@@ -617,9 +738,37 @@ export function createConsole({ port, stateRoot, host, version, log = () => {} }
|
|
|
617
738
|
sessionId: currentSessionId,
|
|
618
739
|
runs: currentSessionId ? lastRuns ?? [] : [],
|
|
619
740
|
approvals: [...approvals.values()].map(entry => entry.payload),
|
|
741
|
+
readNoticeIds: [...noticeRead],
|
|
620
742
|
}
|
|
621
743
|
}
|
|
622
744
|
|
|
745
|
+
/**
|
|
746
|
+
* A conversation opened for the first time in this process (a switch, or a
|
|
747
|
+
* restart where the local timeline only keeps one session) has no cached
|
|
748
|
+
* transcript. Seed it from that session's own committed events so the page
|
|
749
|
+
* shows what happened, rather than an empty thread that looks like lost work.
|
|
750
|
+
*
|
|
751
|
+
* @param {string} sessionId - conversation whose events should be read.
|
|
752
|
+
*/
|
|
753
|
+
async function seedFromHost(sessionId) {
|
|
754
|
+
if (typeof host.readSessionEvents !== 'function') return
|
|
755
|
+
let records
|
|
756
|
+
try {
|
|
757
|
+
records = await host.readSessionEvents(sessionId)
|
|
758
|
+
} catch {
|
|
759
|
+
return
|
|
760
|
+
}
|
|
761
|
+
if (!Array.isArray(records) || records.length === 0) return
|
|
762
|
+
// A live follow may have filled the transcript while this read was in
|
|
763
|
+
// flight; its events are newer and mergeRecords de-duplicates by seq.
|
|
764
|
+
if (store.sessionId !== sessionId) return
|
|
765
|
+
if (store.entries.length > 0) return
|
|
766
|
+
if (mergeRecords(records) === 0) return
|
|
767
|
+
saveTimeline()
|
|
768
|
+
const frame = transcriptFrame()
|
|
769
|
+
if (frame) broadcast({ ...boundedSnapshot(frame), seq: nextSeq(), at: new Date().toISOString() })
|
|
770
|
+
}
|
|
771
|
+
|
|
623
772
|
function openStream(req, res) {
|
|
624
773
|
const caps = capabilities()
|
|
625
774
|
if (!caps.chat) {
|
|
@@ -665,6 +814,7 @@ export function createConsole({ port, stateRoot, host, version, log = () => {} }
|
|
|
665
814
|
writeFrame(res, { type: 'runs', seq: nextSeq(), at: new Date().toISOString(), sessionId: currentSessionId, runs: lastRuns })
|
|
666
815
|
}
|
|
667
816
|
attach(currentSessionId)
|
|
817
|
+
if (!cached) seedFromHost(currentSessionId).catch(() => {})
|
|
668
818
|
const heartbeat = setInterval(() => {
|
|
669
819
|
if (res.destroyed || res.writableEnded) return
|
|
670
820
|
try {
|
|
@@ -750,6 +900,146 @@ export function createConsole({ port, stateRoot, host, version, log = () => {} }
|
|
|
750
900
|
sendText(res, 200, body, type, headers)
|
|
751
901
|
}
|
|
752
902
|
|
|
903
|
+
/**
|
|
904
|
+
* A dropped or pasted file keeps its readable name but loses every path bit
|
|
905
|
+
* and every character Windows reserves, so it can only ever become one file
|
|
906
|
+
* inside the upload directory.
|
|
907
|
+
*
|
|
908
|
+
* @param {unknown} raw - name supplied by the page.
|
|
909
|
+
* @returns {string} a bare file name, possibly empty.
|
|
910
|
+
*/
|
|
911
|
+
function safeUploadName(raw) {
|
|
912
|
+
const base = path.basename(String(raw ?? '').replace(/\\/g, '/'))
|
|
913
|
+
const cleaned = base.replace(/[\u0000-\u001f\u007f<>:"|?*]/g, '').replace(/^\.+/, '').trim()
|
|
914
|
+
return [...cleaned].slice(0, 80).join('')
|
|
915
|
+
}
|
|
916
|
+
|
|
917
|
+
/**
|
|
918
|
+
* Write the bytes under `dir` without ever overwriting an earlier drop.
|
|
919
|
+
*
|
|
920
|
+
* @param {string} dir - upload directory inside the workspace.
|
|
921
|
+
* @param {string} name - bare file name.
|
|
922
|
+
* @param {Buffer} bytes - decoded content.
|
|
923
|
+
* @returns {Promise<string>} the path actually written.
|
|
924
|
+
*/
|
|
925
|
+
async function writeUpload(dir, name, bytes) {
|
|
926
|
+
await fsp.mkdir(dir, { recursive: true })
|
|
927
|
+
const ext = path.extname(name)
|
|
928
|
+
const stem = name.slice(0, name.length - ext.length)
|
|
929
|
+
for (let attempt = 0; attempt < 50; attempt += 1) {
|
|
930
|
+
const candidate = attempt === 0 ? name : `${stem}-${attempt}${ext}`
|
|
931
|
+
const target = path.join(dir, candidate)
|
|
932
|
+
if (!isInside(target, dir)) {
|
|
933
|
+
throw new WorkbenchError(400, '文件名不合法,写不进工作区', { id: 'upload-name' })
|
|
934
|
+
}
|
|
935
|
+
try {
|
|
936
|
+
await fsp.writeFile(target, bytes, { flag: 'wx' })
|
|
937
|
+
return target
|
|
938
|
+
} catch (error) {
|
|
939
|
+
if (error?.code !== 'EEXIST') throw error
|
|
940
|
+
}
|
|
941
|
+
}
|
|
942
|
+
throw new WorkbenchError(409, '同名文件太多了,换个名字再放一次', { id: 'upload-crowded' })
|
|
943
|
+
}
|
|
944
|
+
|
|
945
|
+
/** The per-file cap in words, so both size failures read the same. */
|
|
946
|
+
function uploadCapText() {
|
|
947
|
+
if (uploadLimit >= 1024 * 1024) return `${Math.round(uploadLimit / (1024 * 1024))}MB`
|
|
948
|
+
return `${Math.max(1, Math.round(uploadLimit / 1024))}KB`
|
|
949
|
+
}
|
|
950
|
+
|
|
951
|
+
/**
|
|
952
|
+
* Copy one dropped or pasted file into the conversation's workspace.
|
|
953
|
+
*
|
|
954
|
+
* The page sends bytes and a display name, never a destination: the host
|
|
955
|
+
* resolves the conversation's own workspace and this module keeps the write
|
|
956
|
+
* under it. Unknown extensions are refused instead of sniffed, and the path
|
|
957
|
+
* that would escape the workspace is refused rather than quietly renamed.
|
|
958
|
+
*
|
|
959
|
+
* @param {object} req - the upload request.
|
|
960
|
+
* @param {import('node:http').ServerResponse} res - response sink.
|
|
961
|
+
*/
|
|
962
|
+
async function acceptUpload(req, res) {
|
|
963
|
+
const sessionId = currentSessionId
|
|
964
|
+
if (!sessionId) {
|
|
965
|
+
throw new WorkbenchError(409, '先在对话里说一句话,再把文件放进来', {
|
|
966
|
+
id: 'no-session',
|
|
967
|
+
hint: '文件要落在对话的工作区里,所以先有一条对话。',
|
|
968
|
+
})
|
|
969
|
+
}
|
|
970
|
+
let body
|
|
971
|
+
try {
|
|
972
|
+
body = await readJson(req, { limit: UPLOAD_BODY_LIMIT })
|
|
973
|
+
} catch (error) {
|
|
974
|
+
// The generic body cap speaks about editor saves; a drop deserves a
|
|
975
|
+
// sentence about the file the person just tried to add.
|
|
976
|
+
if (error?.status === 413) {
|
|
977
|
+
throw new WorkbenchError(413, `这个文件太大了,单个文件最多 ${uploadCapText()}`, {
|
|
978
|
+
id: 'upload-too-large',
|
|
979
|
+
hint: '压缩一下再放,或者把文件路径写进消息里让我直接读。',
|
|
980
|
+
})
|
|
981
|
+
}
|
|
982
|
+
throw error
|
|
983
|
+
}
|
|
984
|
+
if (typeof body.sessionId === 'string' && body.sessionId && body.sessionId !== sessionId) {
|
|
985
|
+
throw new WorkbenchError(409, '文件要放进当前对话的工作区', {
|
|
986
|
+
id: 'session-mismatch',
|
|
987
|
+
hint: '刷新页面后再放一次。',
|
|
988
|
+
})
|
|
989
|
+
}
|
|
990
|
+
const name = safeUploadName(body.name)
|
|
991
|
+
if (!name) throw new WorkbenchError(400, '文件名不能为空', { id: 'missing-name' })
|
|
992
|
+
const ext = path.extname(name).toLowerCase()
|
|
993
|
+
if (!UPLOAD_TYPES.has(ext)) {
|
|
994
|
+
throw new WorkbenchError(415, `不能放 ${ext ? `${ext} 文件` : '没有扩展名的文件'}`, {
|
|
995
|
+
id: 'upload-type',
|
|
996
|
+
hint: `可以放:${UPLOAD_TYPES_TEXT}。`,
|
|
997
|
+
})
|
|
998
|
+
}
|
|
999
|
+
const data = typeof body.data === 'string' ? body.data : ''
|
|
1000
|
+
if (!data) throw new WorkbenchError(400, '这个文件没有内容', { id: 'missing-data' })
|
|
1001
|
+
const bytes = Buffer.from(data, 'base64')
|
|
1002
|
+
if (bytes.length === 0) {
|
|
1003
|
+
throw new WorkbenchError(400, '这个文件是空的,或者内容读不出来', { id: 'upload-empty' })
|
|
1004
|
+
}
|
|
1005
|
+
if (bytes.length > uploadLimit) {
|
|
1006
|
+
const mb = (bytes.length / (1024 * 1024)).toFixed(1)
|
|
1007
|
+
throw new WorkbenchError(413, `${name} 有 ${mb}MB,超过单个 ${uploadCapText()} 的上限`, {
|
|
1008
|
+
id: 'upload-too-large',
|
|
1009
|
+
hint: '压缩一下再放,或者把文件路径写进消息里让我直接读。',
|
|
1010
|
+
})
|
|
1011
|
+
}
|
|
1012
|
+
if (typeof host.sessionWorkspace !== 'function') {
|
|
1013
|
+
throw new WorkbenchError(501, 'this host cannot tell the console where its workspace is', {
|
|
1014
|
+
id: 'workspace-unavailable',
|
|
1015
|
+
})
|
|
1016
|
+
}
|
|
1017
|
+
let workspace
|
|
1018
|
+
try {
|
|
1019
|
+
workspace = await host.sessionWorkspace(sessionId)
|
|
1020
|
+
} catch (error) {
|
|
1021
|
+
throw new WorkbenchError(502, `cannot resolve the conversation workspace: ${messageOf(error)}`, {
|
|
1022
|
+
id: 'workspace-unavailable',
|
|
1023
|
+
})
|
|
1024
|
+
}
|
|
1025
|
+
if (typeof workspace !== 'string' || !workspace) {
|
|
1026
|
+
throw new WorkbenchError(502, 'the host returned no workspace for this conversation', {
|
|
1027
|
+
id: 'workspace-unavailable',
|
|
1028
|
+
})
|
|
1029
|
+
}
|
|
1030
|
+
const root = path.resolve(workspace)
|
|
1031
|
+
const folder = sessionId.slice(0, 12).replace(/[^a-zA-Z0-9._-]/g, '')
|
|
1032
|
+
const dir = path.resolve(root, UPLOAD_DIR, folder || 'session')
|
|
1033
|
+
if (!isInside(dir, root) || !isInside(path.join(dir, name), dir)) {
|
|
1034
|
+
throw new WorkbenchError(400, '工作区路径不合法,文件没有落盘', { id: 'upload-escape' })
|
|
1035
|
+
}
|
|
1036
|
+
const target = await writeUpload(dir, name, bytes)
|
|
1037
|
+
send(res, 200, {
|
|
1038
|
+
ok: true,
|
|
1039
|
+
data: { path: target, name: path.basename(target), size: bytes.length, dir },
|
|
1040
|
+
})
|
|
1041
|
+
}
|
|
1042
|
+
|
|
753
1043
|
async function handle(req, res) {
|
|
754
1044
|
try {
|
|
755
1045
|
const parsed = new URL(req.url ?? '/', 'http://127.0.0.1')
|
|
@@ -763,7 +1053,7 @@ export function createConsole({ port, stateRoot, host, version, log = () => {} }
|
|
|
763
1053
|
// allowed from loopback origins only — the token still gates the page.
|
|
764
1054
|
sendText(res, 200, page, 'text/html; charset=utf-8', {
|
|
765
1055
|
'content-security-policy': "default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; "
|
|
766
|
-
+ "connect-src 'self'; img-src 'self' data:; base-uri 'none'; form-action 'none'; "
|
|
1056
|
+
+ "connect-src 'self'; img-src 'self' data:; frame-src 'self'; base-uri 'none'; form-action 'none'; "
|
|
767
1057
|
+ "frame-ancestors 'self' http://127.0.0.1:* http://localhost:* http://[::1]:*",
|
|
768
1058
|
})
|
|
769
1059
|
return
|
|
@@ -809,6 +1099,29 @@ export function createConsole({ port, stateRoot, host, version, log = () => {} }
|
|
|
809
1099
|
return
|
|
810
1100
|
}
|
|
811
1101
|
|
|
1102
|
+
// Notices are derived from durable runs on every load; only the ids a
|
|
1103
|
+
// person has already read need remembering.
|
|
1104
|
+
if (leaf === 'notices' && parts.length === 4 && parts[3] === 'read') {
|
|
1105
|
+
if (method !== 'POST') throw new WorkbenchError(405, 'only POST is allowed here', { id: 'method-not-allowed' })
|
|
1106
|
+
const body = await readJson(req)
|
|
1107
|
+
const ids = Array.isArray(body?.ids)
|
|
1108
|
+
? body.ids
|
|
1109
|
+
.filter(id => typeof id === 'string' && id.trim())
|
|
1110
|
+
.map(id => id.trim())
|
|
1111
|
+
.slice(0, MAX_READ_NOTICES)
|
|
1112
|
+
: []
|
|
1113
|
+
if (ids.length === 0) throw new WorkbenchError(400, 'ids is required', { id: 'missing-ids' })
|
|
1114
|
+
let added = 0
|
|
1115
|
+
for (const id of ids) {
|
|
1116
|
+
if (noticeRead.has(id)) continue
|
|
1117
|
+
noticeRead.add(id)
|
|
1118
|
+
added += 1
|
|
1119
|
+
}
|
|
1120
|
+
if (added > 0) await saveNoticeRead()
|
|
1121
|
+
send(res, 200, { ok: true, data: { read: ids.length, added } })
|
|
1122
|
+
return
|
|
1123
|
+
}
|
|
1124
|
+
|
|
812
1125
|
if (leaf === 'tools' && parts.length === 3) {
|
|
813
1126
|
if (method !== 'GET') throw new WorkbenchError(405, 'only GET is allowed here', { id: 'method-not-allowed' })
|
|
814
1127
|
const sessionId = currentSessionId
|
|
@@ -843,6 +1156,30 @@ export function createConsole({ port, stateRoot, host, version, log = () => {} }
|
|
|
843
1156
|
return
|
|
844
1157
|
}
|
|
845
1158
|
|
|
1159
|
+
if (leaf === 'sessions' && parts.length === 3) {
|
|
1160
|
+
if (method !== 'GET') throw new WorkbenchError(405, 'only GET is allowed here', { id: 'method-not-allowed' })
|
|
1161
|
+
if (typeof host.listSessions !== 'function') {
|
|
1162
|
+
send(res, 200, { ok: true, data: { sessions: [], currentSessionId, reason: 'this host cannot list conversations' } })
|
|
1163
|
+
return
|
|
1164
|
+
}
|
|
1165
|
+
try {
|
|
1166
|
+
const sessions = await host.listSessions()
|
|
1167
|
+
send(res, 200, { ok: true, data: { sessions, currentSessionId, reason: null } })
|
|
1168
|
+
} catch (error) {
|
|
1169
|
+
send(res, 200, { ok: true, data: { sessions: [], currentSessionId, reason: messageOf(error) } })
|
|
1170
|
+
}
|
|
1171
|
+
return
|
|
1172
|
+
}
|
|
1173
|
+
|
|
1174
|
+
if (leaf === 'session' && parts.length === 4 && parts[3] === 'switch') {
|
|
1175
|
+
if (method !== 'POST') throw new WorkbenchError(405, 'only POST is allowed here', { id: 'method-not-allowed' })
|
|
1176
|
+
const body = await readJson(req)
|
|
1177
|
+
const sessionId = typeof body?.sessionId === 'string' ? body.sessionId.trim() : ''
|
|
1178
|
+
if (!sessionId) throw new WorkbenchError(400, 'sessionId is required', { id: 'missing-session-id' })
|
|
1179
|
+
send(res, 200, { ok: true, data: await switchSession(sessionId) })
|
|
1180
|
+
return
|
|
1181
|
+
}
|
|
1182
|
+
|
|
846
1183
|
if (leaf === 'message' && parts.length === 3) {
|
|
847
1184
|
if (method !== 'POST') throw new WorkbenchError(405, 'only POST is allowed here', { id: 'method-not-allowed' })
|
|
848
1185
|
const body = await readJson(req)
|
|
@@ -872,6 +1209,14 @@ export function createConsole({ port, stateRoot, host, version, log = () => {} }
|
|
|
872
1209
|
return
|
|
873
1210
|
}
|
|
874
1211
|
|
|
1212
|
+
// A file dropped on the composer is copied into this conversation's
|
|
1213
|
+
// workspace, then its path is what the page writes into the message.
|
|
1214
|
+
if (leaf === 'upload' && parts.length === 3) {
|
|
1215
|
+
if (method !== 'POST') throw new WorkbenchError(405, 'only POST is allowed here', { id: 'method-not-allowed' })
|
|
1216
|
+
await acceptUpload(req, res)
|
|
1217
|
+
return
|
|
1218
|
+
}
|
|
1219
|
+
|
|
875
1220
|
if (leaf === 'events' && parts.length === 3) {
|
|
876
1221
|
if (method !== 'GET') throw new WorkbenchError(405, 'only GET is allowed here', { id: 'method-not-allowed' })
|
|
877
1222
|
openStream(req, res)
|
|
@@ -882,12 +1227,14 @@ export function createConsole({ port, stateRoot, host, version, log = () => {} }
|
|
|
882
1227
|
if (method !== 'POST') throw new WorkbenchError(405, 'only POST is allowed here', { id: 'method-not-allowed' })
|
|
883
1228
|
const body = await readJson(req)
|
|
884
1229
|
const id = typeof body?.id === 'string' ? body.id.trim() : ''
|
|
885
|
-
const
|
|
1230
|
+
const wanted = body?.decision
|
|
1231
|
+
const decision = wanted === 'allow'
|
|
886
1232
|
? 'allowed-once'
|
|
887
|
-
:
|
|
1233
|
+
: wanted === 'allow-tool' ? 'allowed-tool'
|
|
1234
|
+
: wanted === 'reject' ? 'rejected' : null
|
|
888
1235
|
if (!id) throw new WorkbenchError(400, 'id is required', { id: 'missing-approval-id' })
|
|
889
1236
|
if (!decision) {
|
|
890
|
-
throw new WorkbenchError(400, 'decision must be allow or reject', { id: 'bad-approval-decision' })
|
|
1237
|
+
throw new WorkbenchError(400, 'decision must be allow, allow-tool or reject', { id: 'bad-approval-decision' })
|
|
891
1238
|
}
|
|
892
1239
|
const pending = approvals.get(id)
|
|
893
1240
|
if (!pending) {
|
|
@@ -896,6 +1243,13 @@ export function createConsole({ port, stateRoot, host, version, log = () => {} }
|
|
|
896
1243
|
hint: 'reload the page: the question expired, or another window already answered it.',
|
|
897
1244
|
})
|
|
898
1245
|
}
|
|
1246
|
+
if (decision === 'allowed-tool') {
|
|
1247
|
+
sessionAllowedTools.add(pending.payload.toolName)
|
|
1248
|
+
pending.settle('allowed-once')
|
|
1249
|
+
broadcast({ type: 'approval', action: 'decided', id, outcome: 'allowed-once', scope: 'tool' })
|
|
1250
|
+
send(res, 200, { ok: true, data: { id, outcome: 'allowed-once', scope: 'tool', toolName: pending.payload.toolName } })
|
|
1251
|
+
return
|
|
1252
|
+
}
|
|
899
1253
|
pending.settle(decision)
|
|
900
1254
|
broadcast({ type: 'approval', action: 'decided', id, outcome: decision })
|
|
901
1255
|
send(res, 200, { ok: true, data: { id, outcome: decision } })
|
|
@@ -974,6 +1328,26 @@ export function createConsole({ port, stateRoot, host, version, log = () => {} }
|
|
|
974
1328
|
return
|
|
975
1329
|
}
|
|
976
1330
|
|
|
1331
|
+
if (leaf === 'runs' && parts.length === 5 && parts[4] === 'cancel') {
|
|
1332
|
+
if (method !== 'POST') throw new WorkbenchError(405, 'only POST is allowed here', { id: 'method-not-allowed' })
|
|
1333
|
+
if (!currentSessionId) throw new WorkbenchError(409, 'no conversation is open', { id: 'no-session' })
|
|
1334
|
+
if (typeof host.cancelRun !== 'function') {
|
|
1335
|
+
throw new WorkbenchError(501, 'this host cannot cancel runs from the console', { id: 'cancel-unavailable' })
|
|
1336
|
+
}
|
|
1337
|
+
const runId = decodeURIComponent(parts[3])
|
|
1338
|
+
let result
|
|
1339
|
+
try {
|
|
1340
|
+
result = await host.cancelRun(currentSessionId, runId)
|
|
1341
|
+
} catch (error) {
|
|
1342
|
+
throw new WorkbenchError(502, `the run was not cancelled: ${messageOf(error)}`, { id: 'cancel-failed' })
|
|
1343
|
+
}
|
|
1344
|
+
if (!result) throw new WorkbenchError(404, `no run ${runId} for this conversation`, { id: 'unknown-run' })
|
|
1345
|
+
broadcast({ type: 'canceling', sessionId: currentSessionId, runId, status: result.status })
|
|
1346
|
+
await refreshRuns({ force: true }).catch(() => {})
|
|
1347
|
+
send(res, 200, { ok: true, data: result })
|
|
1348
|
+
return
|
|
1349
|
+
}
|
|
1350
|
+
|
|
977
1351
|
if (leaf === 'runs' && parts.length <= 4) {
|
|
978
1352
|
if (method !== 'GET') throw new WorkbenchError(405, 'only GET is allowed here', { id: 'method-not-allowed' })
|
|
979
1353
|
if (!currentSessionId) {
|