dsh-subscription-agents 0.0.0-stage → 1.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.
- package/LICENSE +21 -0
- package/README.md +159 -2
- package/accounts.js +277 -0
- package/agent-runner.js +227 -0
- package/cli.js +103 -0
- package/client.js +588 -0
- package/codex-usage.js +154 -0
- package/compat.js +31 -0
- package/cordis.patch.yml +12 -0
- package/icon.svg +4 -0
- package/index.js +77 -0
- package/locale/en.json +6 -0
- package/locale/ru.json +6 -0
- package/locale/zh.json +6 -0
- package/native-bridge.js +206 -0
- package/package.json +75 -4
- package/spec/agent-delegation.md +24 -0
- package/spec/subscription-model-picker.md +9 -0
- package/workspace-ui/LICENSE +21 -0
- package/workspace-ui/client.js +5 -0
- package/workspace-ui/icon.svg +1 -0
- package/workspace-ui/index.js +1 -0
- package/workspace-ui/locale/en.json +6 -0
- package/workspace-ui/locale/ru.json +6 -0
- package/workspace-ui/package.json +40 -0
package/codex-usage.js
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process'
|
|
2
|
+
import { StringDecoder } from 'node:string_decoder'
|
|
3
|
+
|
|
4
|
+
const TIMEOUT_MS = 8_000
|
|
5
|
+
const MAX_OUTPUT_BYTES = 256 * 1024 // Per stream; stderr is counted but never retained.
|
|
6
|
+
const TERMINATE_GRACE_MS = 250
|
|
7
|
+
const CLEANUP_TIMEOUT_MS = 750
|
|
8
|
+
const INITIALIZE_ID = 1
|
|
9
|
+
const RATE_LIMITS_ID = 2
|
|
10
|
+
|
|
11
|
+
function windowLabel(minutes, fallback) {
|
|
12
|
+
if (!Number.isSafeInteger(minutes) || minutes <= 0) return fallback
|
|
13
|
+
if (minutes % 1440 === 0) return `${minutes / 1440} d`
|
|
14
|
+
if (minutes % 60 === 0) return `${minutes / 60} h`
|
|
15
|
+
return `${minutes} min`
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function mapWindows(snapshot) {
|
|
19
|
+
const windows = []
|
|
20
|
+
for (const [key, fallback] of [['primary', 'Primary'], ['secondary', 'Secondary']]) {
|
|
21
|
+
const window = snapshot?.[key]
|
|
22
|
+
const usedPercent = window?.usedPercent
|
|
23
|
+
if (!Number.isFinite(usedPercent) || usedPercent < 0) continue
|
|
24
|
+
const mapped = { label: windowLabel(window.windowDurationMins, fallback), usedPercent }
|
|
25
|
+
// Codex sends Unix seconds; the public usage snapshot uses milliseconds.
|
|
26
|
+
if (Number.isSafeInteger(window.resetsAt) && window.resetsAt > 0 && window.resetsAt <= 8.64e12) {
|
|
27
|
+
mapped.resetAt = window.resetsAt * 1000
|
|
28
|
+
}
|
|
29
|
+
windows.push(mapped)
|
|
30
|
+
}
|
|
31
|
+
return windows
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function mapUsage(result) {
|
|
35
|
+
// Read the account's main Codex bucket, not model-specific buckets, credits, or plan metadata.
|
|
36
|
+
let windows = mapWindows(result?.rateLimitsByLimitId?.codex)
|
|
37
|
+
if (windows.length === 0) windows = mapWindows(result?.rateLimits)
|
|
38
|
+
return windows.length > 0 ? { updatedAt: Date.now(), windows } : undefined
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// Only Codex handles its existing account state. No account/login RPCs, local auth reads,
|
|
42
|
+
// or interpretation of errors as login state. Failure is always just unavailable usage.
|
|
43
|
+
export async function readCodexUsage({ exe, argsPrefix = [], env, cwd, signal }) {
|
|
44
|
+
if (!exe || !env || signal?.aborted) return undefined
|
|
45
|
+
let child
|
|
46
|
+
try {
|
|
47
|
+
child = spawn(exe, [...argsPrefix, 'app-server', '--listen', 'stdio://'], {
|
|
48
|
+
cwd,
|
|
49
|
+
env,
|
|
50
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
51
|
+
windowsHide: true,
|
|
52
|
+
})
|
|
53
|
+
} catch {
|
|
54
|
+
return undefined
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
return new Promise((resolve) => {
|
|
58
|
+
const decoder = new StringDecoder('utf8')
|
|
59
|
+
let pending = ''
|
|
60
|
+
let stdoutBytes = 0
|
|
61
|
+
let stderrBytes = 0
|
|
62
|
+
let expectedId = INITIALIZE_ID
|
|
63
|
+
let result
|
|
64
|
+
let finishing = false
|
|
65
|
+
let killTimer
|
|
66
|
+
let cleanupTimer
|
|
67
|
+
const timeout = setTimeout(() => finish(), TIMEOUT_MS)
|
|
68
|
+
|
|
69
|
+
function abort() { finish() }
|
|
70
|
+
|
|
71
|
+
function complete() {
|
|
72
|
+
clearTimeout(killTimer)
|
|
73
|
+
clearTimeout(cleanupTimer)
|
|
74
|
+
resolve(signal?.aborted ? undefined : result)
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function terminate(signalName) {
|
|
78
|
+
if (child.pid && child.exitCode === null && child.signalCode === null) {
|
|
79
|
+
try { child.kill(signalName) } catch { /* No child diagnostics leave this module. */ }
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function finish(value, closed = false) {
|
|
84
|
+
if (finishing) return
|
|
85
|
+
finishing = true
|
|
86
|
+
result = value
|
|
87
|
+
clearTimeout(timeout)
|
|
88
|
+
signal?.removeEventListener('abort', abort)
|
|
89
|
+
pending = ''
|
|
90
|
+
child.stdin.destroy()
|
|
91
|
+
child.stdout.destroy()
|
|
92
|
+
child.stderr.destroy()
|
|
93
|
+
if (closed) return complete()
|
|
94
|
+
terminate('SIGTERM')
|
|
95
|
+
killTimer = setTimeout(() => terminate('SIGKILL'), TERMINATE_GRACE_MS)
|
|
96
|
+
cleanupTimer = setTimeout(() => {
|
|
97
|
+
child.unref()
|
|
98
|
+
complete()
|
|
99
|
+
}, CLEANUP_TIMEOUT_MS)
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function send(...messages) {
|
|
103
|
+
try {
|
|
104
|
+
child.stdin.write(messages.map((message) => JSON.stringify(message) + '\n').join(''))
|
|
105
|
+
} catch {
|
|
106
|
+
finish()
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
child.once('close', () => {
|
|
111
|
+
if (finishing) complete()
|
|
112
|
+
else finish(undefined, true)
|
|
113
|
+
})
|
|
114
|
+
child.on('error', () => finish())
|
|
115
|
+
for (const stream of [child.stdin, child.stdout, child.stderr]) {
|
|
116
|
+
stream.on('error', () => finish())
|
|
117
|
+
}
|
|
118
|
+
child.stderr.on('data', (chunk) => {
|
|
119
|
+
stderrBytes += chunk.length
|
|
120
|
+
if (stderrBytes > MAX_OUTPUT_BYTES) finish()
|
|
121
|
+
})
|
|
122
|
+
child.stdout.on('data', (chunk) => {
|
|
123
|
+
stdoutBytes += chunk.length
|
|
124
|
+
if (stdoutBytes > MAX_OUTPUT_BYTES) return finish()
|
|
125
|
+
pending += decoder.write(chunk)
|
|
126
|
+
let newline
|
|
127
|
+
while (!finishing && (newline = pending.indexOf('\n')) !== -1) {
|
|
128
|
+
const line = pending.slice(0, newline)
|
|
129
|
+
pending = pending.slice(newline + 1)
|
|
130
|
+
if (!line.trim()) continue
|
|
131
|
+
let message
|
|
132
|
+
try { message = JSON.parse(line) } catch { return finish() }
|
|
133
|
+
// Notifications and any server-initiated requests are not quota responses.
|
|
134
|
+
if (message?.method !== undefined || message?.id !== expectedId) continue
|
|
135
|
+
if (Object.hasOwn(message, 'error') || !message.result || typeof message.result !== 'object') {
|
|
136
|
+
return finish()
|
|
137
|
+
}
|
|
138
|
+
if (expectedId === INITIALIZE_ID) {
|
|
139
|
+
expectedId = RATE_LIMITS_ID
|
|
140
|
+
send({ method: 'initialized' }, { id: RATE_LIMITS_ID, method: 'account/rateLimits/read' })
|
|
141
|
+
} else {
|
|
142
|
+
return finish(mapUsage(message.result))
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
})
|
|
146
|
+
signal?.addEventListener('abort', abort, { once: true })
|
|
147
|
+
if (signal?.aborted) return finish()
|
|
148
|
+
send({
|
|
149
|
+
id: INITIALIZE_ID,
|
|
150
|
+
method: 'initialize',
|
|
151
|
+
params: { clientInfo: { name: 'dsh_subscription_agents', version: '1.0.0' } },
|
|
152
|
+
})
|
|
153
|
+
})
|
|
154
|
+
}
|
package/compat.js
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
// Host methods this plugin calls. Checked before anything is registered or written,
|
|
2
|
+
// so a DSH update that renames one of them stops the plugin with a clear message
|
|
3
|
+
// instead of failing halfway through a session.
|
|
4
|
+
export const REQUIRED_HOST_API = [
|
|
5
|
+
'effect', 'on', 'emit',
|
|
6
|
+
'connection.fetch.register',
|
|
7
|
+
'tools.register',
|
|
8
|
+
'subagents.startActivation', 'subagents.resolveMaxDepth', 'subagents.registerProvider',
|
|
9
|
+
'llm.registerAdapter',
|
|
10
|
+
'agents.list', 'agents.get', 'agents.turnBoundaryOf',
|
|
11
|
+
'sandboxPolicy.resolve',
|
|
12
|
+
'workingDirectory.ensure', 'workingDirectory.get',
|
|
13
|
+
];
|
|
14
|
+
|
|
15
|
+
export function missingHostApi(ctx, required = REQUIRED_HOST_API) {
|
|
16
|
+
const missing = required.filter(path => {
|
|
17
|
+
const parts = path.split('.');
|
|
18
|
+
let owner = ctx;
|
|
19
|
+
for (const part of parts.slice(0, -1)) owner = owner?.[part];
|
|
20
|
+
return typeof owner?.[parts.at(-1)] !== 'function';
|
|
21
|
+
});
|
|
22
|
+
if (typeof ctx?.profileContext?.dir !== 'string') missing.push('profileContext.dir');
|
|
23
|
+
return missing;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function assertHostApi(ctx) {
|
|
27
|
+
const missing = missingHostApi(ctx);
|
|
28
|
+
if (missing.length) {
|
|
29
|
+
throw new Error(`dsh-subscription-agents: this DSH build lacks ${missing.join(', ')}. Update the plugin for this DSH version; nothing was registered.`);
|
|
30
|
+
}
|
|
31
|
+
}
|
package/cordis.patch.yml
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
# The bundle owns the workspace UI replacement; disable it to restore the shipped UI.
|
|
2
|
+
# Fully restart Desktop after changing this service provider.
|
|
3
|
+
# Relative module paths are resolved next to this file, so the bundle can live anywhere.
|
|
4
|
+
- id: ui-workspace
|
|
5
|
+
disabled: true
|
|
6
|
+
- insert:
|
|
7
|
+
- id: subscription-workspace-ui
|
|
8
|
+
name: './workspace-ui/index.js'
|
|
9
|
+
config: {}
|
|
10
|
+
- id: subscription-agents
|
|
11
|
+
name: 'dsh-subscription-agents'
|
|
12
|
+
config: {}
|
package/icon.svg
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
<svg xmlns="http://www.w3.org/2000/svg" width="36" height="36" viewBox="0 0 36 36" fill="none">
|
|
2
|
+
<path d="M9 12h18M9 18h18M9 24h18" stroke="#718096" stroke-width="2.2" stroke-linecap="round"/>
|
|
3
|
+
<path d="M9 12h13M9 18h8M9 24h16" stroke="#6083D6" stroke-width="3.3" stroke-linecap="round"/>
|
|
4
|
+
</svg>
|
package/index.js
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { join } from 'node:path';
|
|
2
|
+
import { makeService } from './accounts.js';
|
|
3
|
+
import { installNativeBridge } from './native-bridge.js';
|
|
4
|
+
import { randomUUID } from 'node:crypto';
|
|
5
|
+
import { assertHostApi } from './compat.js';
|
|
6
|
+
|
|
7
|
+
export const inject = ['connection','tools','profileContext','subagents','llm','agents','sandboxPolicy','workingDirectory'];
|
|
8
|
+
const path = '/api/subscription-agents';
|
|
9
|
+
const json = (value, status=200) => Response.json(value, {status,headers:{'Cache-Control':'no-store','X-Content-Type-Options':'nosniff'}});
|
|
10
|
+
|
|
11
|
+
export async function apply(ctx) {
|
|
12
|
+
assertHostApi(ctx);
|
|
13
|
+
const service = await makeService(join(ctx.profileContext.dir, 'subscription-agents'), {
|
|
14
|
+
onCatalogChanged(provider) {
|
|
15
|
+
try { ctx.emit('llm/models-updated', `dsh-subscription-${provider}`); }
|
|
16
|
+
catch (error) { ctx.logger.warn(error); }
|
|
17
|
+
},
|
|
18
|
+
});
|
|
19
|
+
ctx.effect(() => () => service.dispose());
|
|
20
|
+
await installNativeBridge(ctx,service);
|
|
21
|
+
ctx.effect(() => ctx.connection.fetch.register({
|
|
22
|
+
path, methods:['POST'], requestBody:'streaming',
|
|
23
|
+
async fetch(request) {
|
|
24
|
+
if (request.headers.get('x-dsh-subscription-agents') !== '1' || request.headers.get('sec-fetch-site') === 'cross-site' || request.headers.get('content-type')?.split(';')[0] !== 'application/json') {
|
|
25
|
+
return json({ok:false,error:'Запрос отклонён.'},403);
|
|
26
|
+
}
|
|
27
|
+
try {
|
|
28
|
+
const reader = request.body?.getReader();
|
|
29
|
+
if (!reader) return json({ok:false,error:'Пустой запрос.'},400);
|
|
30
|
+
const chunks = []; let size = 0;
|
|
31
|
+
while (true) {
|
|
32
|
+
const {done,value} = await reader.read();
|
|
33
|
+
if (done) break;
|
|
34
|
+
size += value.byteLength;
|
|
35
|
+
if (size > 8192) { await reader.cancel(); return json({ok:false,error:'Слишком большой запрос.'},413); }
|
|
36
|
+
chunks.push(value);
|
|
37
|
+
}
|
|
38
|
+
let data;
|
|
39
|
+
try { data = JSON.parse(Buffer.concat(chunks).toString('utf8')); }
|
|
40
|
+
catch { return json({ok:false,error:'Неверный JSON.'},400); }
|
|
41
|
+
return json(await service.action(data, {user:true,signal:request.signal}));
|
|
42
|
+
} catch {
|
|
43
|
+
return json({ok:false,error:'Не удалось выполнить действие. Проверьте состояние аккаунта.'},500);
|
|
44
|
+
}
|
|
45
|
+
},
|
|
46
|
+
}));
|
|
47
|
+
const properties = {action:{enum:['list','refresh','test','delegate'],type:'string'},id:{type:'string',description:'Account ID for refresh or test.'},provider:{enum:['codex','claude'],type:'string',description:'Optional CLI preference; omit to pick the available account with most fresh quota.'},prompt:{type:'string',description:'Task for a full CLI agent. It has access to the current project and built-in file and command tools. Specify the files it owns; avoid concurrent edits to the same files.',maxLength:70000},name:{type:'string',description:'Optional short agent name, lower-case letters, digits and hyphens.'},description:{type:'string',description:'Short task label displayed in the child chat.'}};
|
|
48
|
+
ctx.effect(() => ctx.tools.register({
|
|
49
|
+
name:'subscription_agent',
|
|
50
|
+
description:'Delegate project work to a full Codex or Claude Code agent using an enabled subscription account. Returns the child name immediately; a completion notice follows. Its ordinary DSH child chat preserves prompts, replies and CLI tool activity. Follow up with send_message, inspect list_agents, and interrupt through native subagent controls. Prefer this for independent project tasks; review the final diff and tests yourself. Never retry a quota failure through another account automatically.',
|
|
51
|
+
parameters:{type:'object',properties,required:['action'],additionalProperties:false},
|
|
52
|
+
output:{schema:{type:'object',properties:{ok:{type:'boolean'},error:{type:'string'},text:{type:'string'},accounts:{type:'array'},available:{type:'object'},account:{type:'object'},childId:{type:'string'},name:{type:'string'},messageId:{type:'string'}},required:['ok'],additionalProperties:false}, render(_args,value){return [{type:'text',text:JSON.stringify(value)}];}},
|
|
53
|
+
timeoutMs:205000,
|
|
54
|
+
isConcurrencySafe:()=>true,
|
|
55
|
+
async execute(args,exec) {
|
|
56
|
+
try {
|
|
57
|
+
if (args?.action !== 'delegate') return await service.action(args,{signal:exec.signal});
|
|
58
|
+
if (!exec.agent || typeof args.prompt !== 'string' || !args.prompt.trim() || args.prompt.length > 70000 || (args.provider !== undefined && !['codex','claude'].includes(args.provider))) return {ok:false,error:'Некорректная задача агента.'};
|
|
59
|
+
const parent = exec.agent;
|
|
60
|
+
if (ctx.sandboxPolicy.resolve({session:parent.session}).mode !== 'danger-full-access') return {ok:false,error:'Полноценный CLI-агент пока доступен только в сессии с полным доступом. Ограничения DSH не будут обходиться.'};
|
|
61
|
+
const account = service.pick(args.provider);
|
|
62
|
+
if (!account) return {ok:false,error:'Нет свободного подключённого аккаунта с разрешённым делегированием.'};
|
|
63
|
+
const activation = await ctx.subagents.startActivation({
|
|
64
|
+
provider:'subscription-cli', childId:randomUUID(), parent, signal:exec.signal,
|
|
65
|
+
prompt:[{type:'text',text:args.prompt}], label:typeof args.description==='string' ? args.description.trim().slice(0,120) || `${account.provider} · ${account.name}` : `${account.provider} · ${account.name}`,
|
|
66
|
+
...(args.name ? {name:args.name} : {}), delivery:'parent',
|
|
67
|
+
cwd:await ctx.workingDirectory.ensure(parent,exec.signal),
|
|
68
|
+
agentOptions:{provider:`dsh-subscription-${account.provider}`,model:account.id},
|
|
69
|
+
maxDepth:ctx.subagents.resolveMaxDepth(),
|
|
70
|
+
});
|
|
71
|
+
activation.result.catch(()=>{});
|
|
72
|
+
return {ok:true,childId:activation.childId,name:activation.name,messageId:activation.messageId,account:{number:account.number,provider:account.provider,name:account.name}};
|
|
73
|
+
}
|
|
74
|
+
catch { return {ok:false,error:'Не удалось выполнить операцию подписки.'}; }
|
|
75
|
+
},
|
|
76
|
+
}));
|
|
77
|
+
}
|
package/locale/en.json
ADDED
package/locale/ru.json
ADDED
package/locale/zh.json
ADDED
package/native-bridge.js
ADDED
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
import { LlmAdapter } from '@deepseek-ai/dsh-llm';
|
|
2
|
+
import { randomUUID } from 'node:crypto';
|
|
3
|
+
import { mkdir, readFile, writeFile, rename } from 'node:fs/promises';
|
|
4
|
+
import { join } from 'node:path';
|
|
5
|
+
|
|
6
|
+
const ROUTES = { 'dsh-subscription-codex': 'codex', 'dsh-subscription-claude': 'claude' };
|
|
7
|
+
const LABELS = { codex:'Codex', claude:'Claude Code' };
|
|
8
|
+
const MAX_TEXT = 2_000_000;
|
|
9
|
+
const MAX_CHAT_HISTORY = 80_000;
|
|
10
|
+
const routeProvider = route => ROUTES[route];
|
|
11
|
+
const isChild = session => session.header?.origin === 'subagent';
|
|
12
|
+
const chatUser = m => m.role === 'user' && (!m.source || m.source.kind === 'user');
|
|
13
|
+
const chatText = m => m.content.filter(b => b.type === 'text').map(b => b.text).join('\n');
|
|
14
|
+
function promptOf(messages) {
|
|
15
|
+
let start = 0;
|
|
16
|
+
for (let i = 0; i < messages.length; i++) if (messages[i].role === 'assistant') start = i + 1;
|
|
17
|
+
const users = messages.slice(start).filter(m => m.role === 'user' && !['runtime-context','subagent-return'].includes(m.source?.kind));
|
|
18
|
+
if (users.some(m => m.content.some(b => b.type !== 'text'))) throw new Error('CLI child currently accepts text prompts only; image and file attachments are not supported.');
|
|
19
|
+
const prompt = users.flatMap(m => m.content.map(b => b.text)).join('\n\n');
|
|
20
|
+
if (!prompt.trim() || prompt.length > 100_000) throw new Error('CLI child requires a nonempty text prompt within 100,000 characters.');
|
|
21
|
+
return prompt;
|
|
22
|
+
}
|
|
23
|
+
function chatPromptOf(messages) {
|
|
24
|
+
let start = messages.length;
|
|
25
|
+
while (start > 0) {
|
|
26
|
+
const previous = messages[start - 1];
|
|
27
|
+
if (previous.role === 'assistant' && chatText(previous).trim()) break;
|
|
28
|
+
start--;
|
|
29
|
+
}
|
|
30
|
+
const current = messages.slice(start).filter(chatUser);
|
|
31
|
+
if (current.some(m => m.content.some(b => b.type !== 'text'))) throw new Error('Subscription chats accept text only; attachments are not supported.');
|
|
32
|
+
const prompt = current.map(chatText).join('\n\n');
|
|
33
|
+
if (!prompt.trim() || prompt.length > 100_000) throw new Error('Subscription chat requires a nonempty text prompt within 100,000 characters.');
|
|
34
|
+
const history = [];
|
|
35
|
+
let bytes = 0;
|
|
36
|
+
for (let i = start - 1; i >= 0; i--) {
|
|
37
|
+
const m = messages[i];
|
|
38
|
+
if (m.role !== 'assistant' && !chatUser(m)) continue;
|
|
39
|
+
const text = chatText(m);
|
|
40
|
+
if (!text.trim()) continue;
|
|
41
|
+
const line = JSON.stringify({ role:m.role,text });
|
|
42
|
+
bytes += Buffer.byteLength(line) + 1;
|
|
43
|
+
if (bytes > MAX_CHAT_HISTORY) break;
|
|
44
|
+
history.push(line);
|
|
45
|
+
}
|
|
46
|
+
if (!history.length) return prompt;
|
|
47
|
+
return `Previous chat messages (JSON lines, for context):\n${history.reverse().join('\n')}\n\nCurrent user request:\n${prompt}`;
|
|
48
|
+
}
|
|
49
|
+
function modelInfo(provider, account) {
|
|
50
|
+
return { provider, id:account.id, name:`${LABELS[account.provider]} · подписка · ${account.name}`, inputModalities:['text'] };
|
|
51
|
+
}
|
|
52
|
+
function* textBlock(index, text) {
|
|
53
|
+
yield { type:'block-start', index, blockType:'text' };
|
|
54
|
+
yield { type:'text-delta', index, text };
|
|
55
|
+
yield { type:'block-end', index, block:{ type:'text',text } };
|
|
56
|
+
}
|
|
57
|
+
/** Install continuable native child sessions routed through official CLI turns. */
|
|
58
|
+
export async function installNativeBridge(ctx, service) {
|
|
59
|
+
const root = join(ctx.profileContext.dir, 'subscription-agents');
|
|
60
|
+
await mkdir(root, { recursive: true, mode: 0o700 });
|
|
61
|
+
const path = join(root, 'native-threads.json');
|
|
62
|
+
let threads;
|
|
63
|
+
try { threads = JSON.parse(await readFile(path, 'utf8')); }
|
|
64
|
+
catch (error) { if (error.code !== 'ENOENT') throw error; threads = {}; }
|
|
65
|
+
if (!threads || typeof threads !== 'object' || Array.isArray(threads)) throw new Error('Invalid CLI thread registry');
|
|
66
|
+
let writes = Promise.resolve();
|
|
67
|
+
function persist() {
|
|
68
|
+
const text = JSON.stringify(threads);
|
|
69
|
+
const next = writes.catch(() => {}).then(async () => {
|
|
70
|
+
const temp = join(root, `native-threads-${randomUUID()}.tmp`);
|
|
71
|
+
await writeFile(temp, text, { mode: 0o600 });
|
|
72
|
+
await rename(temp, path);
|
|
73
|
+
});
|
|
74
|
+
writes = next;
|
|
75
|
+
return next;
|
|
76
|
+
}
|
|
77
|
+
const cleanups = new Map();
|
|
78
|
+
const life = new AbortController();
|
|
79
|
+
ctx.effect(() => () => { life.abort(); for (const dispose of cleanups.values()) dispose(); cleanups.clear(); return writes; });
|
|
80
|
+
function configure(agent) {
|
|
81
|
+
if (!isChild(agent.session) || !routeProvider(agent.model.current()?.provider) || cleanups.has(agent)) return;
|
|
82
|
+
const dispose = agent.ctx.effect(() => agent.ctx.tools.restrict({ allow: [] }));
|
|
83
|
+
cleanups.set(agent, dispose);
|
|
84
|
+
}
|
|
85
|
+
ctx.on('agent/created', ({ agent }) => configure(agent));
|
|
86
|
+
ctx.on('agent/disposed', ({ agent }) => { cleanups.delete(agent); });
|
|
87
|
+
for (const agent of ctx.agents.list()) configure(agent);
|
|
88
|
+
class CliAdapter extends LlmAdapter {
|
|
89
|
+
providerInfo(provider) { return { id: provider, name: `${LABELS[routeProvider(provider)]} · подписка` }; }
|
|
90
|
+
providerRetryPolicy() { return { mode: 'normal', maxRetries: 0, retryableCodes: [], initialDelayMs: 1000, maxDelayMs: 1000, jitterRatio: 0 }; }
|
|
91
|
+
async listModels(provider) {
|
|
92
|
+
return service.modelAccounts(routeProvider(provider)).map(account => modelInfo(provider,account));
|
|
93
|
+
}
|
|
94
|
+
async resolveModel(provider, model) {
|
|
95
|
+
const account = service.modelAccounts(routeProvider(provider)).find(row => row.id === model);
|
|
96
|
+
if (!account) throw new Error('Подписочный аккаунт недоступен. Проверьте вход и переключатель в панели «Подписочные агенты».');
|
|
97
|
+
return modelInfo(provider,account);
|
|
98
|
+
}
|
|
99
|
+
async *stream(options) {
|
|
100
|
+
if (options.purpose !== undefined) throw new Error('Subscription CLI does not handle auxiliary model requests.');
|
|
101
|
+
const agent = ctx.agents.get(options.sessionId);
|
|
102
|
+
if (!agent || agent.model.current()?.provider !== options.provider || agent.model.current()?.model !== options.model) throw new Error('CLI route requires the selected account on its live Session.');
|
|
103
|
+
const policy = ctx.sandboxPolicy.resolve({ session: agent.session });
|
|
104
|
+
if (policy.mode !== 'danger-full-access') throw new Error('CLI workspace execution requires Full access in this release; restricted DSH policies cannot yet be enforced by this bridge.');
|
|
105
|
+
const cwd = ctx.workingDirectory.get(agent.session);
|
|
106
|
+
const provider = routeProvider(options.provider);
|
|
107
|
+
const session = agent.session;
|
|
108
|
+
const child = isChild(session);
|
|
109
|
+
const position = ctx.agents.turnBoundaryOf(session);
|
|
110
|
+
const stepEvent = position.lastStepStartSeq === null ? undefined : session.eventAt(position.lastStepStartSeq);
|
|
111
|
+
if (position.openTurnStartSeq === null || stepEvent?.type !== 'step/start') throw new Error('CLI turn has no open DSH step');
|
|
112
|
+
const { turn, step } = stepEvent.data;
|
|
113
|
+
const key = session.id;
|
|
114
|
+
const old = child && Object.hasOwn(threads, key) ? threads[key] : undefined;
|
|
115
|
+
if (old && (old.account !== options.model || old.provider !== provider)) throw new Error('CLI account cannot be switched inside an existing child');
|
|
116
|
+
const operationController = new AbortController();
|
|
117
|
+
const signal = AbortSignal.any([life.signal, operationController.signal, ...(options.signal ? [options.signal] : [])]);
|
|
118
|
+
const calls = new Map();
|
|
119
|
+
const pendingText = [];
|
|
120
|
+
let failure, result, closed = false, settled = false, wake, bytes = 0, textCount = 0;
|
|
121
|
+
const appendResult = (call, output, isError) => session.append('tool/result', {
|
|
122
|
+
turn, step, message: { id: randomUUID(), role: 'tool', source: { kind: 'tool', callId: call.id }, toolCallId: call.id, content: [{ type: 'text', text: String(output ?? '').slice(0, 100_000) }], ...(isError ? { isError: true } : {}) },
|
|
123
|
+
}, { surfaceOp: 'append' });
|
|
124
|
+
function enqueueText(text) {
|
|
125
|
+
if (!text.trim()) return;
|
|
126
|
+
bytes += Buffer.byteLength(text);
|
|
127
|
+
if (bytes > MAX_TEXT || ++textCount > 4096) throw new Error('CLI turn output exceeded the transcript limit');
|
|
128
|
+
pendingText.push(text);
|
|
129
|
+
wake?.();
|
|
130
|
+
}
|
|
131
|
+
async function onEvent(event) {
|
|
132
|
+
if (closed || signal.aborted) return;
|
|
133
|
+
if (event.type === 'thread' && typeof event.id === 'string' && /^[a-zA-Z0-9_-]{1,200}$/.test(event.id)) {
|
|
134
|
+
if (!child) return;
|
|
135
|
+
threads[key] = { account: options.model, provider, threadId: event.id };
|
|
136
|
+
try { await persist(); } catch (error) { operationController.abort(); throw error; }
|
|
137
|
+
} else if (event.type === 'text' && typeof event.text === 'string') {
|
|
138
|
+
enqueueText(event.text);
|
|
139
|
+
} else if (event.type === 'tool-start') {
|
|
140
|
+
const remoteId = String(event.id);
|
|
141
|
+
if (calls.has(remoteId)) return;
|
|
142
|
+
const name = `subscription_cli_${String(event.name ?? 'tool').replace(/[^a-zA-Z0-9_]/g, '_').slice(0, 70)}`;
|
|
143
|
+
const args = typeof event.args === 'string' ? event.args : JSON.stringify(event.args ?? {});
|
|
144
|
+
const call = { id: randomUUID(), name, arguments: args.slice(0, 100_000) };
|
|
145
|
+
session.append([
|
|
146
|
+
['assistant/message', { turn, step, message: { id: randomUUID(), role: 'assistant', source: { kind: 'model', provider: options.provider, model: options.model }, content: [{ type: 'tool-call', ...call }] }, stream: [] }, { surfaceOp: 'append' }],
|
|
147
|
+
['tool/call', { turn, step, callId: call.id, name, arguments: call.arguments }],
|
|
148
|
+
]);
|
|
149
|
+
calls.set(remoteId, call);
|
|
150
|
+
} else if (event.type === 'tool-end') {
|
|
151
|
+
const remoteId = String(event.id);
|
|
152
|
+
const call = calls.get(remoteId);
|
|
153
|
+
if (call) { appendResult(call, event.text, Boolean(event.isError)); calls.delete(remoteId); }
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
const operation = Promise.resolve().then(() => service.runAgentTurn(options.model, {
|
|
157
|
+
cwd, permissionMode: 'workspace-write', threadId: old?.threadId, expectedProvider:provider, ephemeral:!child,
|
|
158
|
+
prompt: child ? promptOf(options.messages) : chatPromptOf(options.messages), signal, onEvent,
|
|
159
|
+
})).then(value => { result = value; }, error => { failure = error; }).finally(() => {
|
|
160
|
+
settled = true;
|
|
161
|
+
wake?.();
|
|
162
|
+
});
|
|
163
|
+
try {
|
|
164
|
+
let index = 0;
|
|
165
|
+
while (pendingText.length || !settled) {
|
|
166
|
+
if (!pendingText.length) {
|
|
167
|
+
await new Promise(resolve => { wake = resolve; });
|
|
168
|
+
wake = undefined;
|
|
169
|
+
continue;
|
|
170
|
+
}
|
|
171
|
+
if (signal.aborted) throw new Error('CLI turn canceled');
|
|
172
|
+
yield* textBlock(index++, pendingText.shift());
|
|
173
|
+
}
|
|
174
|
+
await operation;
|
|
175
|
+
if (child && result?.threadId && threads[key]?.threadId !== result.threadId) {
|
|
176
|
+
threads[key] = { account: options.model, provider, threadId: result.threadId };
|
|
177
|
+
await persist();
|
|
178
|
+
}
|
|
179
|
+
if (child) await writes;
|
|
180
|
+
if (failure) throw failure;
|
|
181
|
+
if (result?.ok === false) throw new Error(result.error || 'CLI turn failed');
|
|
182
|
+
if (signal.aborted) throw new Error('CLI turn canceled');
|
|
183
|
+
if (index === 0) {
|
|
184
|
+
if (typeof result?.text !== 'string' || !result.text.trim()) throw new Error('CLI завершил ход, но не вернул ответ.');
|
|
185
|
+
yield* textBlock(index, result.text);
|
|
186
|
+
}
|
|
187
|
+
yield { type: 'finish', reason: { kind: 'stop' } };
|
|
188
|
+
} finally {
|
|
189
|
+
closed = true;
|
|
190
|
+
operationController.abort();
|
|
191
|
+
await operation;
|
|
192
|
+
for (const call of calls.values()) appendResult(call, 'CLI execution ended without a confirmed tool result. Do not assume the operation was completed.', true);
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
ctx.effect(() => ctx.llm.registerAdapter(Object.keys(ROUTES), new CliAdapter()));
|
|
197
|
+
ctx.effect(() => ctx.subagents.registerProvider({
|
|
198
|
+
name: 'subscription-cli', inheritsParentContext: false,
|
|
199
|
+
capabilities: { agentOptions: true, agentPreset: false, outputSchema: false, depthLimit: true },
|
|
200
|
+
async prepareContinuable({ parent }) {
|
|
201
|
+
if (ctx.sandboxPolicy.resolve({ session: parent.session }).mode !== 'danger-full-access') throw new Error('CLI agents currently require Full access.');
|
|
202
|
+
return {};
|
|
203
|
+
},
|
|
204
|
+
}));
|
|
205
|
+
return { provider: 'subscription-cli', route: provider => provider === 'codex' ? 'dsh-subscription-codex' : 'dsh-subscription-claude' };
|
|
206
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,77 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-subscription-agents",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.2.0",
|
|
4
|
+
"description": "Use local Codex and Claude Code subscription accounts as DeepSeek Harness models and continuable child agents.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"dsh-plugin",
|
|
7
|
+
"deepseek-harness",
|
|
8
|
+
"codex",
|
|
9
|
+
"claude-code",
|
|
10
|
+
"subagents",
|
|
11
|
+
"ai-agents"
|
|
12
|
+
],
|
|
13
|
+
"homepage": "https://github.com/adsqwui/dsh-subscription-agents#readme",
|
|
14
|
+
"bugs": {
|
|
15
|
+
"url": "https://github.com/adsqwui/dsh-subscription-agents/issues"
|
|
16
|
+
},
|
|
17
|
+
"repository": {
|
|
18
|
+
"type": "git",
|
|
19
|
+
"url": "git+https://github.com/adsqwui/dsh-subscription-agents.git"
|
|
20
|
+
},
|
|
21
|
+
"license": "MIT",
|
|
22
|
+
"author": "adsqwui",
|
|
23
|
+
"type": "module",
|
|
24
|
+
"exports": {
|
|
25
|
+
".": "./index.js",
|
|
26
|
+
"./client": "./client.js",
|
|
27
|
+
"./locale/*.json": "./locale/*.json",
|
|
28
|
+
"./icon": "./icon.svg"
|
|
29
|
+
},
|
|
30
|
+
"files": [
|
|
31
|
+
"index.js",
|
|
32
|
+
"accounts.js",
|
|
33
|
+
"agent-runner.js",
|
|
34
|
+
"native-bridge.js",
|
|
35
|
+
"compat.js",
|
|
36
|
+
"cli.js",
|
|
37
|
+
"codex-usage.js",
|
|
38
|
+
"client.js",
|
|
39
|
+
"cordis.patch.yml",
|
|
40
|
+
"locale/*.json",
|
|
41
|
+
"icon.svg",
|
|
42
|
+
"workspace-ui/index.js",
|
|
43
|
+
"workspace-ui/client.js",
|
|
44
|
+
"workspace-ui/package.json",
|
|
45
|
+
"workspace-ui/LICENSE",
|
|
46
|
+
"workspace-ui/icon.svg",
|
|
47
|
+
"workspace-ui/locale/*.json",
|
|
48
|
+
"README.md",
|
|
49
|
+
"LICENSE",
|
|
50
|
+
"spec"
|
|
51
|
+
],
|
|
52
|
+
"scripts": {
|
|
53
|
+
"test": "node --test *.test.js"
|
|
54
|
+
},
|
|
55
|
+
"engines": {
|
|
56
|
+
"dsh": ">=0.2.2-rc.3 <0.3.0-0"
|
|
57
|
+
},
|
|
58
|
+
"peerDependencies": {
|
|
59
|
+
"@deepseek-ai/dsh-llm": ">=0.2.2-rc.3 <0.3.0-0"
|
|
60
|
+
},
|
|
61
|
+
"dsh": {
|
|
62
|
+
"bundle": {
|
|
63
|
+
"patch": "./cordis.patch.yml"
|
|
64
|
+
},
|
|
65
|
+
"client": {
|
|
66
|
+
"platform": "web",
|
|
67
|
+
"immediately": true,
|
|
68
|
+
"inject": [
|
|
69
|
+
"@deepseek-ai/dsh-client-ui-sidebar",
|
|
70
|
+
"@deepseek-ai/dsh-client-ui-layout",
|
|
71
|
+
"@deepseek-ai/dsh-client-ui-session",
|
|
72
|
+
"@deepseek-ai/dsh-client-ui-workspace",
|
|
73
|
+
"@deepseek-ai/dsh-client-locale"
|
|
74
|
+
]
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
# Граница делегирования
|
|
2
|
+
|
|
3
|
+
DeepSeek Harness управляет дочерними сессиями подписочного плагина. Каждый
|
|
4
|
+
запуск Codex, новый или возобновлённый, выполняет задание напрямую:
|
|
5
|
+
`multi_agent` и `multi_agent_v2` отключаются только в аргументах процесса.
|
|
6
|
+
Для отдельного исполнителя нужно создать отдельный дочерний чат в Harness.
|
|
7
|
+
|
|
8
|
+
Плагин сохраняет привязку к аккаунту и идентификатору сессии Codex,
|
|
9
|
+
передаёт завершённые сообщения и вывод инструментов в дочерний чат.
|
|
10
|
+
Настройки Codex за пределами плагина и запуск Claude Code не меняются.
|
|
11
|
+
|
|
12
|
+
Для совместимости с событиями старых сессий: `wait` без адресатов,
|
|
13
|
+
состояний и ошибки не попадает в ленту. Если эти данные приходят только
|
|
14
|
+
при завершении вызова, лента получает одну пару «вызов → результат»
|
|
15
|
+
с фактическими данными. Завершение `wait` не завершает ход.
|
|
16
|
+
|
|
17
|
+
Прошлые чаты не переписываются. Исправление не меняет поведение при
|
|
18
|
+
сетевых переподключениях, не запускает повторно отменённые задания
|
|
19
|
+
и не переключает аккаунты.
|
|
20
|
+
|
|
21
|
+
Приёмка: `node --test`, затем короткий smoke в приложении на задаче
|
|
22
|
+
без внешних инструментов (например, попросить описать один локальный файл).
|
|
23
|
+
В дочернем чате должны быть видны результат и ответ на уточнение в том
|
|
24
|
+
же чате. Запуск через подписку проверяется отдельно от unit-тестов.
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
# Подписки в селекторе модели
|
|
2
|
+
|
|
3
|
+
- Штатный селектор и `/model` показывают профиль каждого включённого подписочного аккаунта, который прошёл проверку входа и CLI. Codex и Claude Code отображаются отдельными группами. Название указывает провайдера и профиль, а конкретную модель выбирают настройки официального CLI.
|
|
4
|
+
- Статус входа, включение, выключение, переименование и удаление обновляют каталог без перезапуска. Текущая занятость и квота не убирают строку из каталога.
|
|
5
|
+
- Обычный чат выполняет запрос на выбранном аккаунте без API-ключей, автоматических повторов и переключения на другой аккаунт или API. Сбой, отсутствие CLI и исчерпание лимита возвращаются как ошибки.
|
|
6
|
+
- Обычные чаты не привязывают вендорскую сессию: каждый ход передаёт актуальный текст и до 80 000 символов видимого текстового контекста. Можно менять провайдера между ходами; выбор отправляет контекст этого чата выбранному провайдеру. Вложения текущего запроса не поддерживаются. Служебные сообщения и сырые результаты инструментов не включаются в контекст. Подписочный дочерний чат сохраняет прежнюю привязку к аккаунту и CLI-сессии.
|
|
7
|
+
- CLI выполняет команды в рабочем каталоге проекта по существующим правилам плагина и требует режим Harness «Полный доступ». Селектор не повышает права. Инструменты CLI записываются в историю, но не исполняются второй раз ядром Harness.
|
|
8
|
+
- Для обычного и дочернего чатов текст CLI передаётся штатными блоками потока Harness. Так итоговый ответ отображается в самом ходе, а не остаётся скрытой записью в журнале. Если CLI завершился без текста, ход показывает ошибку вместо пустого успешного завершения.
|
|
9
|
+
- Несвязанные с ходом вспомогательные вызовы не записывают результат в чат. Подключение и подтверждение подписки остаются в панели «Подписочные агенты».
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 DeepSeek
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|