dsh-subscription-agents 0.0.0-stage → 1.2.1
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 +251 -0
- package/cli.js +111 -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/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 adsqwui
|
|
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.
|
package/README.md
CHANGED
|
@@ -1,3 +1,160 @@
|
|
|
1
|
-
|
|
1
|
+
<p align="center">
|
|
2
|
+
<img src="docs/banner.jpg" alt="dsh-subscription-agents: Codex and Claude Code subscriptions as DeepSeek Harness agents" width="100%">
|
|
3
|
+
</p>
|
|
2
4
|
|
|
3
|
-
|
|
5
|
+
<p align="center">
|
|
6
|
+
<a href="https://github.com/adsqwui/dsh-subscription-agents/actions/workflows/test.yml"><img alt="tests" src="https://github.com/adsqwui/dsh-subscription-agents/actions/workflows/test.yml/badge.svg"></a>
|
|
7
|
+
<a href="https://www.npmjs.com/package/dsh-subscription-agents"><img alt="npm" src="https://img.shields.io/npm/v/dsh-subscription-agents?color=cb3837&logo=npm"></a>
|
|
8
|
+
<img alt="DeepSeek Harness 0.2.x" src="https://img.shields.io/badge/DeepSeek%20Harness-0.2.x-4d6bfe">
|
|
9
|
+
<img alt="Node 22+" src="https://img.shields.io/badge/node-%3E%3D22-339933?logo=node.js&logoColor=white">
|
|
10
|
+
<img alt="macOS" src="https://img.shields.io/badge/platform-macOS-lightgrey?logo=apple">
|
|
11
|
+
<a href="LICENSE"><img alt="MIT license" src="https://img.shields.io/github/license/adsqwui/dsh-subscription-agents"></a>
|
|
12
|
+
<a href="CONTRIBUTING.md"><img alt="PRs welcome" src="https://img.shields.io/badge/PRs-welcome-brightgreen"></a>
|
|
13
|
+
</p>
|
|
14
|
+
|
|
15
|
+
<p align="center">
|
|
16
|
+
Run the official <b>Codex</b> and <b>Claude Code</b> CLIs on your own subscriptions as models and continuable child agents inside <a href="https://github.com/deepseek-ai/deepseek-harness">DeepSeek Harness</a>.
|
|
17
|
+
</p>
|
|
18
|
+
|
|
19
|
+
---
|
|
20
|
+
|
|
21
|
+
<p align="center">
|
|
22
|
+
<img src="docs/screenshot-accounts.png" alt="The Subscription agents panel with a Codex and a Claude Code account" width="90%">
|
|
23
|
+
</p>
|
|
24
|
+
|
|
25
|
+
## Why
|
|
26
|
+
|
|
27
|
+
You already pay for ChatGPT or Claude. DeepSeek Harness is a good place to run agents. This plugin connects the two without API keys, proxies or patched binaries. It drives the **unmodified** official CLIs you installed yourself, gives each account its own isolated profile, and shows their work as ordinary DSH chats you can read, continue and interrupt.
|
|
28
|
+
|
|
29
|
+
## Features
|
|
30
|
+
|
|
31
|
+
- **Accounts panel.** Add Codex and Claude Code accounts, sign in through the vendor's own browser flow, run a one-word smoke test, then switch delegation on. Rename, refresh, sign out and remove from the same card.
|
|
32
|
+
- **Subscriptions in the model picker.** A tested account shows up next to your other models (and in `/model`). The account's CLI picks the actual model.
|
|
33
|
+
- **Real child agents.** The `subscription_agent` tool starts a native, continuable DSH child chat and returns its name at once. The lead gets a completion notice; `send_message` resumes the same account and vendor thread.
|
|
34
|
+
- **Full transcript.** Child chats show the delegated prompt, every finished assistant message and the CLI's tool calls with their results. Nothing is invented: hidden reasoning and nested vendor agents are not faked.
|
|
35
|
+
- **Nested sidebar.** Child chats fold under their parent in the workspace sidebar.
|
|
36
|
+
- **Quota you can see.** Codex limit windows come from the Codex App Server; Claude Code windows come from its stream events. The tightest fresh window decides which account has the most headroom.
|
|
37
|
+
- **Agent limits at a glance.** A compact list of every account and its current limit sits at the bottom of the left sidebar.
|
|
38
|
+
- **Fails closed.** Restricted sessions, unknown DSH versions, missing CLIs and quota errors stop the task with a clear message instead of quietly doing something else.
|
|
39
|
+
|
|
40
|
+
## How it works
|
|
41
|
+
|
|
42
|
+
```mermaid
|
|
43
|
+
flowchart LR
|
|
44
|
+
lead["DSH lead agent"] -- "subscription_agent" --> child["Native DSH child chat"]
|
|
45
|
+
picker["Model picker"] --> chat["Regular DSH chat"]
|
|
46
|
+
child --> bridge["CLI bridge"]
|
|
47
|
+
chat --> bridge
|
|
48
|
+
bridge --> pick{"Account choice"}
|
|
49
|
+
pick --> codex["codex exec<br/>CODEX_HOME per account"]
|
|
50
|
+
pick --> claude["claude -p<br/>CLAUDE_CONFIG_DIR per account"]
|
|
51
|
+
codex -. "JSONL events" .-> bridge
|
|
52
|
+
claude -. "stream-json events" .-> bridge
|
|
53
|
+
bridge -- "messages, tool calls, results" --> child
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
The bridge starts one CLI turn per DSH turn, reads its JSON event stream with bounded buffers, and writes the messages and tool activity into the DSH session. Each child chat pins one account and one vendor thread, so follow-ups continue the same conversation on the vendor side. Regular chats pass recent visible text to a fresh CLI turn instead, which is what lets you switch accounts or providers mid-conversation.
|
|
57
|
+
|
|
58
|
+
## Requirements
|
|
59
|
+
|
|
60
|
+
| | |
|
|
61
|
+
|---|---|
|
|
62
|
+
| DeepSeek Harness | Desktop **0.2.2-rc.3** or any later **0.2.x**. The manifest declares `engines.dsh: ">=0.2.2-rc.3 <0.3.0-0"`. |
|
|
63
|
+
| OS | macOS |
|
|
64
|
+
| CLIs | Official `codex` and/or `claude`, already installed and on `PATH` (`~/.local/bin`, `/opt/homebrew/bin`, `/usr/local/bin` are searched) |
|
|
65
|
+
| Session | **Full access** for agent work and subscription chats |
|
|
66
|
+
|
|
67
|
+
## Install
|
|
68
|
+
|
|
69
|
+
In DSH open **Plugins → Add plugin**, enter the package name and install:
|
|
70
|
+
|
|
71
|
+
```text
|
|
72
|
+
dsh-subscription-agents
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
Enable it, then fully restart Desktop: the nested sidebar replaces the shipped one, and that only happens on restart. From a terminal the same is `dsh plugin --profile <profile> add dsh-subscription-agents`.
|
|
76
|
+
|
|
77
|
+
To work on the code instead, clone the repository and give **Add plugin** the absolute path of the folder. DSH links to it, so `git pull` and a restart are all an update takes.
|
|
78
|
+
|
|
79
|
+
## Usage
|
|
80
|
+
|
|
81
|
+
### Connect an account
|
|
82
|
+
|
|
83
|
+
1. Open **Subscription agents** in the left sidebar and press **Add account**.
|
|
84
|
+
2. Pick Codex or Claude Code and give it a local name.
|
|
85
|
+
3. Press **Sign in** and finish the vendor's flow in your browser. If no browser opens, use the sign-in link the card shows.
|
|
86
|
+
4. The plugin runs one minimal "OK" request. **Test** repeats it at any time.
|
|
87
|
+
5. Switch **Delegation** on. Switching it off later stops new tasks and cancels a running one where possible.
|
|
88
|
+
|
|
89
|
+
**Remove** also asks the CLI to sign out locally. It does not revoke the vendor's browser session.
|
|
90
|
+
|
|
91
|
+
### Chat with a subscription
|
|
92
|
+
|
|
93
|
+
Pick **Codex · подписка · <name>** or **Claude Code · подписка · <name>** in the model picker or with `/model`. The conversation runs through that account only. If its CLI is missing or out of quota, the turn fails; the plugin never falls back to another route or reads API keys. Attachments are not supported yet. See the [model picker spec](spec/subscription-model-picker.md).
|
|
94
|
+
|
|
95
|
+
### Delegate work
|
|
96
|
+
|
|
97
|
+
Ask the lead agent to hand a task off, or let it call `subscription_agent` itself:
|
|
98
|
+
|
|
99
|
+
```text
|
|
100
|
+
Delegate to a Claude Code subscription agent: add tests for src/parser.ts
|
|
101
|
+
and fix whatever they catch. You own src/parser.ts and its tests only.
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
The child chat appears under its parent. Open it to watch progress or to send a follow-up. For parallel work, give independent tasks to separate children: each Codex process works on its own, with nested Codex agents turned off. See the [delegation spec](spec/agent-delegation.md).
|
|
105
|
+
|
|
106
|
+
## Safety and permissions
|
|
107
|
+
|
|
108
|
+
- **Full access only.** CLI permissions cannot reproduce DSH's filesystem confinement, so restricted sessions are refused instead of being quietly widened.
|
|
109
|
+
- **No silent approvals.** Codex runs with `workspace-write` and no interactive approvals. Claude Code runs with `acceptEdits` and denies unanswered permission prompts, so arbitrary shell commands are not auto-approved.
|
|
110
|
+
- **Isolated credentials.** Codex accounts use their own `CODEX_HOME` with CLI-managed file auth. Claude Code accounts use their own `CLAUDE_CONFIG_DIR` and the macOS Keychain where available. Your existing CLI profiles are never imported or touched. Do not copy or share the plugin's private state folder.
|
|
111
|
+
- **Recorded, not replayed.** Tool calls the CLI made are written into the transcript but are never executed again through DSH.
|
|
112
|
+
- **Guarded start.** On start the plugin checks every DSH Host method it uses. If an update renamed or removed one, it stops with an error naming it and registers nothing.
|
|
113
|
+
|
|
114
|
+
## Quota and account choice
|
|
115
|
+
|
|
116
|
+
Codex snapshots refresh about every three minutes and after each request. Claude Code reports windows only when its stream includes them, and the plugin never sends paid background prompts to find out. A snapshot older than six minutes, or one past its reset time, no longer affects the choice. Among enabled accounts, the one with the most headroom in its tightest fresh window wins; accounts with unknown quota come after accounts with known headroom. A quota error is never retried on another account.
|
|
117
|
+
|
|
118
|
+
## Compatibility
|
|
119
|
+
|
|
120
|
+
The plugin accepts every DSH **0.2.x** release and refuses **0.3** until it has been checked against it. The nested sidebar in `workspace-ui/` is a patched build of DSH's MIT-licensed `ui-workspace` package from `dsh-v0.2.2-rc.3` (unchanged upstream through rc.5). To see whether a newer DSH changed it, run this in a DSH source checkout:
|
|
121
|
+
|
|
122
|
+
```bash
|
|
123
|
+
git diff --stat dsh-v0.2.2-rc.3 <new-tag> -- packages/client/ui-workspace/src
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
Empty output means the bundled sidebar is still current. Otherwise re-apply `workspace-ui/native-tree.patch` to the new source, rebuild with `workspace-ui/tsdown.config.ts` (it expects the DSH checkout at `../../deepseek-harness-src` relative to `workspace-ui`) and run `node workspace-ui/finalize-build.mjs`. Disabling the bundle always brings the stock sidebar back.
|
|
127
|
+
|
|
128
|
+
## Development
|
|
129
|
+
|
|
130
|
+
```bash
|
|
131
|
+
npm test
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
The suite runs on Node 22 and 24 on Linux and macOS in CI. It needs no DSH install and no CLI logins: the CLIs and the Host are replaced with fakes.
|
|
135
|
+
|
|
136
|
+
| File | What it does |
|
|
137
|
+
|---|---|
|
|
138
|
+
| `index.js` | Registers the panel API and the `subscription_agent` tool |
|
|
139
|
+
| `accounts.js` | Account store, sign-in, tests, quota and account choice |
|
|
140
|
+
| `cli.js` | Spawns the CLIs with isolated environments and parses their output |
|
|
141
|
+
| `agent-runner.js` | Runs one persistent CLI turn and normalizes its events |
|
|
142
|
+
| `native-bridge.js` | LLM adapter and subagent provider that write CLI turns into DSH sessions |
|
|
143
|
+
| `codex-usage.js` | Reads Codex limit windows from the App Server |
|
|
144
|
+
| `compat.js` | Checks the DSH Host API before anything registers |
|
|
145
|
+
| `client.js` | The accounts panel and the Agent limits list |
|
|
146
|
+
| `workspace-ui/` | The nested workspace sidebar |
|
|
147
|
+
|
|
148
|
+
## Contributing
|
|
149
|
+
|
|
150
|
+
Bug reports, ideas and pull requests are welcome. Read [CONTRIBUTING.md](CONTRIBUTING.md) first; it covers the setup, what a good PR looks like, and the few rules that keep accounts safe.
|
|
151
|
+
|
|
152
|
+
## Before you use it
|
|
153
|
+
|
|
154
|
+
Subscription plans from OpenAI and Anthropic are meant for a person using the vendor's own apps. Driving the official CLIs from another program, and especially spreading work over several subscriptions to stay under their limits, may break those vendors' terms, and accounts can be rate-limited or suspended for it. This project hides nothing from the vendors and will not help you get around a ban. Use it only with accounts you own, read the current terms yourself, and accept that the risk is yours.
|
|
155
|
+
|
|
156
|
+
References: [Codex non-interactive mode](https://learn.chatgpt.com/docs/non-interactive-mode) · [Codex App Server](https://developers.openai.com/codex/app-server) · [Claude Code authentication](https://code.claude.com/docs/en/authentication) · [Claude Code legal and compliance](https://code.claude.com/docs/en/legal-and-compliance#authentication-and-credential-use)
|
|
157
|
+
|
|
158
|
+
## License
|
|
159
|
+
|
|
160
|
+
[MIT](LICENSE). `workspace-ui/` contains code from DeepSeek Harness, also MIT; its notice is kept in [`workspace-ui/LICENSE`](workspace-ui/LICENSE). Not affiliated with DeepSeek, OpenAI or Anthropic.
|
package/accounts.js
ADDED
|
@@ -0,0 +1,277 @@
|
|
|
1
|
+
import { mkdir, chmod, readFile, writeFile, rename, rm } from 'node:fs/promises';
|
|
2
|
+
import { isAbsolute, join } from 'node:path';
|
|
3
|
+
import { randomUUID } from 'node:crypto';
|
|
4
|
+
import { cliEnv, command, executable, inference, run, subscribed, codexPrefix, callTimeout } from './cli.js';
|
|
5
|
+
import { readCodexUsage } from './codex-usage.js';
|
|
6
|
+
import { runAgent } from './agent-runner.js';
|
|
7
|
+
|
|
8
|
+
const providers = ['codex','claude'];
|
|
9
|
+
const names = {codex:'ChatGPT / Codex',claude:'Claude Code'};
|
|
10
|
+
const fail = message => ({ok:false,error:message});
|
|
11
|
+
const ok = value => ({ok:true,...value});
|
|
12
|
+
const LIMIT = 24;
|
|
13
|
+
const FRESH = 6 * 60_000;
|
|
14
|
+
export function remaining(a, now = Date.now()) {
|
|
15
|
+
if (!a.usage || now - a.usage.updatedAt >= FRESH || !a.usage.windows.length || a.usage.windows.some(w => now - (w.sampledAt ?? a.usage.updatedAt) >= FRESH || (w.resetAt && w.resetAt <= now))) return undefined;
|
|
16
|
+
return Math.min(...a.usage.windows.map(w => 100 - w.usedPercent));
|
|
17
|
+
}
|
|
18
|
+
export function pickAccount(accounts, provider, now = Date.now()) {
|
|
19
|
+
return accounts.filter(a => a.enabled && a.status === 'ready' && !a.busy && !(a.cooldown > now) && (!provider || a.provider === provider) && remaining(a, now) !== 0)
|
|
20
|
+
.sort((a,b) => (remaining(b, now) ?? -1) - (remaining(a, now) ?? -1) || (a.lastUsed ?? 0)-(b.lastUsed ?? 0) || a.number-b.number)[0];
|
|
21
|
+
}
|
|
22
|
+
export async function makeService(root, options = {}) {
|
|
23
|
+
if (!isAbsolute(root)) throw new Error('Expected an absolute profile directory');
|
|
24
|
+
const cliRun = options.run ?? run, resolve = options.executable ?? executable, getUsage = options.readCodexUsage ?? readCodexUsage;
|
|
25
|
+
const life = new AbortController();
|
|
26
|
+
const cwd = join(root,'empty');
|
|
27
|
+
const file = join(root,'accounts.json');
|
|
28
|
+
await mkdir(cwd,{recursive:true,mode:0o700}); await chmod(root,0o700);
|
|
29
|
+
let db;
|
|
30
|
+
try { db = JSON.parse(await readFile(file,'utf8')); } catch(e) { if (e.code !== 'ENOENT') throw e; db = {next:1, accounts:[]}; }
|
|
31
|
+
if (!Number.isSafeInteger(db.next) || db.next < 1 || !Array.isArray(db.accounts) || db.accounts.some(a => !/^[a-f0-9-]{36}$/.test(a.id) || !providers.includes(a.provider))) throw new Error('Invalid subscription account data');
|
|
32
|
+
const active = new Map();
|
|
33
|
+
const modelAccounts = provider => db.accounts
|
|
34
|
+
.filter(a => a.provider === provider && a.enabled && a.status === 'ready' && a.testPassed === true)
|
|
35
|
+
.map(({id,name,provider,number}) => ({id,name,provider,number}));
|
|
36
|
+
const catalogs = new Map(providers.map(provider => [provider,JSON.stringify(modelAccounts(provider))]));
|
|
37
|
+
function publishCatalogChanges() {
|
|
38
|
+
for (const provider of providers) {
|
|
39
|
+
const catalog = JSON.stringify(modelAccounts(provider));
|
|
40
|
+
if (catalog === catalogs.get(provider)) continue;
|
|
41
|
+
catalogs.set(provider,catalog);
|
|
42
|
+
options.onCatalogChanged?.(provider);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
let writes = Promise.resolve();
|
|
46
|
+
const persist = () => {
|
|
47
|
+
const serialized = JSON.stringify(db, (k,v) => ['busy','loginUrl'].includes(k) ? undefined : v);
|
|
48
|
+
const commit = writes.catch(() => {}).then(async () => {
|
|
49
|
+
const temp = join(root,'accounts.tmp');
|
|
50
|
+
await writeFile(temp,serialized,{mode:0o600}); await rename(temp,file);
|
|
51
|
+
publishCatalogChanges();
|
|
52
|
+
});
|
|
53
|
+
writes = commit; return commit;
|
|
54
|
+
};
|
|
55
|
+
let lastDiscovery = 0, discovered = {};
|
|
56
|
+
async function availability() {
|
|
57
|
+
if (Date.now()-lastDiscovery > 15_000) {
|
|
58
|
+
discovered = Object.fromEntries(await Promise.all(providers.map(async provider => [provider,await resolve(provider)])));
|
|
59
|
+
lastDiscovery = Date.now();
|
|
60
|
+
}
|
|
61
|
+
return discovered;
|
|
62
|
+
}
|
|
63
|
+
const dir = a => join(root, a.id);
|
|
64
|
+
function view(a, user = false) {
|
|
65
|
+
return Object.fromEntries(['id','number','provider','name','enabled','status','busy','note','usage','checkedAt','testPassed',...(user ? ['loginUrl'] : [])].filter(k=>a[k]!==undefined).map(k=>[k,a[k]]));
|
|
66
|
+
}
|
|
67
|
+
function start(a, busy, fn, parent) {
|
|
68
|
+
if (active.has(a.id)) return;
|
|
69
|
+
const controller = new AbortController();
|
|
70
|
+
const signal = AbortSignal.any([life.signal, controller.signal, ...(parent ? [parent] : [])]);
|
|
71
|
+
a.busy = busy;
|
|
72
|
+
const task = Promise.resolve().then(() => fn(signal)).catch(e => {
|
|
73
|
+
a.note = signal.aborted ? 'Операция отменена.' : e.message;
|
|
74
|
+
if (busy === 'login') a.status = 'error';
|
|
75
|
+
return fail(a.note);
|
|
76
|
+
}).finally(async () => {
|
|
77
|
+
delete a.loginUrl;
|
|
78
|
+
delete a.busy;
|
|
79
|
+
try { await persist(); } finally { active.delete(a.id); }
|
|
80
|
+
});
|
|
81
|
+
active.set(a.id,{controller,task,busy});
|
|
82
|
+
return task;
|
|
83
|
+
}
|
|
84
|
+
async function execute(a, op, signal, opts) {
|
|
85
|
+
const exe = (await availability())[a.provider];
|
|
86
|
+
if (!exe) throw new Error(`Не найден официальный CLI: ${names[a.provider]}.`);
|
|
87
|
+
const profile = dir(a);
|
|
88
|
+
await mkdir(profile,{mode:0o700,recursive:true});
|
|
89
|
+
return cliRun(exe, command(a.provider,op), { cwd, env:cliEnv(a.provider,profile), signal, ...opts });
|
|
90
|
+
}
|
|
91
|
+
async function status(a, signal) {
|
|
92
|
+
const valid = subscribed(a.provider, await execute(a,'status',signal));
|
|
93
|
+
a.checkedAt = Date.now();
|
|
94
|
+
a.status = valid ? 'ready' : 'new';
|
|
95
|
+
if (!valid) { delete a.usage; a.note = 'CLI не подтвердил вход по подписке.'; }
|
|
96
|
+
return valid;
|
|
97
|
+
}
|
|
98
|
+
async function quota(a, signal) {
|
|
99
|
+
if (a.provider !== 'codex') return;
|
|
100
|
+
const exe = (await availability())[a.provider];
|
|
101
|
+
if (!exe) return;
|
|
102
|
+
try {
|
|
103
|
+
const usage = await getUsage({exe,argsPrefix:codexPrefix,cwd,env:cliEnv(a.provider,dir(a)),signal});
|
|
104
|
+
if (usage) a.usage = usage;
|
|
105
|
+
} catch { /* An unavailable snapshot is not zero usage. */ }
|
|
106
|
+
}
|
|
107
|
+
async function invoke(a, prompt, signal, testing = false) {
|
|
108
|
+
if (testing) {
|
|
109
|
+
a.testPassed = false;
|
|
110
|
+
publishCatalogChanges();
|
|
111
|
+
}
|
|
112
|
+
if (!await status(a,signal)) return fail(a.note);
|
|
113
|
+
const raw = await execute(a,'infer',signal,{input:prompt,timeout: testing ? 75_000 : callTimeout});
|
|
114
|
+
const reply = inference(a.provider,raw);
|
|
115
|
+
if (reply.usage) {
|
|
116
|
+
const previous = a.usage?.windows.filter(w => Date.now() - (w.sampledAt ?? a.usage.updatedAt) < FRESH && (!w.resetAt || w.resetAt > Date.now())) ?? [];
|
|
117
|
+
const windows = new Map(previous.map(w => [w.label,w]));
|
|
118
|
+
for (const w of reply.usage.windows) windows.set(w.label,{...w,sampledAt:reply.usage.updatedAt});
|
|
119
|
+
a.usage = {...reply.usage,windows:[...windows.values()]};
|
|
120
|
+
}
|
|
121
|
+
await quota(a,signal);
|
|
122
|
+
if (signal.aborted) return fail('Операция отменена.');
|
|
123
|
+
a.lastUsed = Date.now();
|
|
124
|
+
if (reply.error || (testing && reply.text !== 'OK')) {
|
|
125
|
+
a.note = reply.error === 'quota' ? 'CLI сообщил о лимите. Повтор автоматически не запускается.' : reply.error === 'auth' ? 'Авторизация CLI не подтверждена. Войдите заново.' : testing && reply.text ? 'CLI ответил, но не вернул ожидаемое OK.' : 'CLI не вернул результат.';
|
|
126
|
+
if (reply.error === 'auth') a.status = 'new';
|
|
127
|
+
if (reply.error === 'quota') a.cooldown = Date.now() + 5*60_000;
|
|
128
|
+
return fail(a.note);
|
|
129
|
+
}
|
|
130
|
+
delete a.cooldown;
|
|
131
|
+
if (testing) a.testPassed = true;
|
|
132
|
+
a.note = testing ? 'Проверка пройдена: CLI ответил OK.' : 'Последняя задача завершена.';
|
|
133
|
+
return ok({account:{number:a.number,provider:a.provider,name:a.name},text:reply.text});
|
|
134
|
+
}
|
|
135
|
+
function refresh(a) {
|
|
136
|
+
if (a.busy || a.status !== 'ready') return;
|
|
137
|
+
return start(a,'refresh',async signal => { if (await status(a,signal)) await quota(a,signal); });
|
|
138
|
+
}
|
|
139
|
+
function background(p) { p?.catch(() => {}); }
|
|
140
|
+
const interval = setInterval(() => { for (const a of db.accounts) if (a.provider === 'codex') background(refresh(a)); },180_000);
|
|
141
|
+
interval.unref?.();
|
|
142
|
+
async function action(body, {user=false, signal}={}) {
|
|
143
|
+
if (life.signal.aborted || !body || typeof body !== 'object' || Array.isArray(body)) return fail('Некорректный запрос.');
|
|
144
|
+
if (!user && !['list','refresh','test','delegate'].includes(body.action)) return fail('Это действие доступно только пользователю в панели.');
|
|
145
|
+
if (body.action === 'list') {
|
|
146
|
+
const av = await availability();
|
|
147
|
+
return ok({accounts:db.accounts.map(a=>view(a,user)),available:Object.fromEntries(providers.map(p=>[p,Boolean(av[p])]))});
|
|
148
|
+
}
|
|
149
|
+
if (body.action === 'add') {
|
|
150
|
+
if (!providers.includes(body.provider) || db.accounts.length >= LIMIT || !(await availability())[body.provider]) return fail('CLI не найден, выбран неверный тип или достигнут предел аккаунтов.');
|
|
151
|
+
if (db.accounts.length >= LIMIT) return fail('Достигнут предел аккаунтов.');
|
|
152
|
+
const number = db.next++;
|
|
153
|
+
const a = {id:randomUUID(),number,provider:body.provider,name:cleanName(body.name) || `${names[body.provider]} #${number}`,enabled:false,status:'new'};
|
|
154
|
+
db.accounts.push(a); await persist(); return ok({account:view(a)});
|
|
155
|
+
}
|
|
156
|
+
if (body.action === 'delegate') {
|
|
157
|
+
if (user || typeof body.prompt !== 'string' || !body.prompt.trim() || body.prompt.length > 70_000 || (body.provider != null && !providers.includes(body.provider))) return fail('Неверный запрос делегирования.');
|
|
158
|
+
const a = pickAccount(db.accounts,body.provider);
|
|
159
|
+
if (!a) return fail('Нет подключённого свободного аккаунта с разрешением на делегирование.');
|
|
160
|
+
return fail('Для делегирования используйте управляемую дочернюю сессию.');
|
|
161
|
+
}
|
|
162
|
+
if (body.action === 'refresh' && !body.id) { for (const a of db.accounts) background(refresh(a)); return ok({}); }
|
|
163
|
+
const a = db.accounts.find(x => x.id === body.id);
|
|
164
|
+
if (!a) return fail('Аккаунт не найден.');
|
|
165
|
+
if (body.action === 'cancel') {
|
|
166
|
+
const work = active.get(a.id);
|
|
167
|
+
if (work && ['login','test','refresh'].includes(work.busy)) work.controller.abort();
|
|
168
|
+
return ok({});
|
|
169
|
+
}
|
|
170
|
+
if (body.action === 'toggle' && body.enabled === false) {
|
|
171
|
+
a.enabled = false;
|
|
172
|
+
const work = active.get(a.id);
|
|
173
|
+
if (work?.busy === 'delegate') work.controller.abort();
|
|
174
|
+
await persist(); return ok({});
|
|
175
|
+
}
|
|
176
|
+
if (a.busy) return fail('Аккаунт занят.');
|
|
177
|
+
if (body.action === 'rename') {
|
|
178
|
+
if (!cleanName(body.name)) return fail('Введите имя аккаунта.');
|
|
179
|
+
a.name = cleanName(body.name); await persist(); return ok({});
|
|
180
|
+
}
|
|
181
|
+
if (body.action === 'toggle') {
|
|
182
|
+
if (a.status !== 'ready' || a.testPassed !== true || body.enabled !== true) return fail('Сначала войдите в аккаунт и пройдите проверку CLI.');
|
|
183
|
+
a.enabled = true; await persist(); return ok({});
|
|
184
|
+
}
|
|
185
|
+
if (body.action === 'login') {
|
|
186
|
+
if (db.accounts.some(x=>x.busy === 'login')) return fail('Сначала завершите предыдущий вход.');
|
|
187
|
+
a.enabled = false; a.testPassed = false; a.status = 'login'; delete a.usage;
|
|
188
|
+
publishCatalogChanges();
|
|
189
|
+
a.note = 'Завершите вход в браузере на этом компьютере.';
|
|
190
|
+
background(start(a,'login',async signal => {
|
|
191
|
+
const result = await execute(a,'login',signal,{timeout:300_000,onOutput:(out,err)=>{
|
|
192
|
+
if (!a.loginUrl) a.loginUrl = officialLoginUrl(a.provider,out+'\n'+err);
|
|
193
|
+
}});
|
|
194
|
+
if (result.code !== 0 || !await status(a,signal)) {a.status='error'; a.note='CLI не подтвердил вход. Попробуйте снова.'; return;}
|
|
195
|
+
a.busy = 'test'; delete a.loginUrl;
|
|
196
|
+
a.note = 'Вход подтверждён. Выполняется проверка CLI.';
|
|
197
|
+
const resultTest = await invoke(a,'Reply with exactly OK. No explanation.',signal,true).catch(e => fail(e.message));
|
|
198
|
+
if (!resultTest.ok && a.status === 'ready') a.note = `Вход выполнен. ${a.note}`;
|
|
199
|
+
}));
|
|
200
|
+
return ok({});
|
|
201
|
+
}
|
|
202
|
+
if (body.action === 'refresh') {
|
|
203
|
+
background(start(a,'refresh',async signal => {if (await status(a,signal)) await quota(a,signal);})); return ok({});
|
|
204
|
+
}
|
|
205
|
+
if (body.action === 'test') {
|
|
206
|
+
if (!user && !a.enabled) return fail('Сначала разрешите делегирование для этого аккаунта в панели.');
|
|
207
|
+
const task = start(a,'test',signal=>invoke(a,'Reply with exactly OK. No explanation.',signal,true));
|
|
208
|
+
if (!user) return task;
|
|
209
|
+
background(task); return ok({});
|
|
210
|
+
}
|
|
211
|
+
if (body.action === 'remove') {
|
|
212
|
+
return start(a,'remove',async signal => {
|
|
213
|
+
if (a.status === 'ready' || a.checkedAt || a.provider === 'claude') {
|
|
214
|
+
const result = await execute(a,'logout',signal);
|
|
215
|
+
if (result.code !== 0) return fail('CLI не подтвердил выход; аккаунт не удалён.');
|
|
216
|
+
}
|
|
217
|
+
// Only a validated UUID child of our private state directory may be removed.
|
|
218
|
+
const target = dir(a);
|
|
219
|
+
if (target !== join(root,a.id) || !/^[a-f0-9-]{36}$/.test(a.id)) return fail('Неверный каталог аккаунта.');
|
|
220
|
+
await rm(target,{recursive:true,force:true});
|
|
221
|
+
db.accounts = db.accounts.filter(x=>x!==a);
|
|
222
|
+
return ok({});
|
|
223
|
+
});
|
|
224
|
+
}
|
|
225
|
+
return fail('Неизвестное действие.');
|
|
226
|
+
}
|
|
227
|
+
for (const a of db.accounts) if (a.status === 'login') { a.status='new'; a.note='Прошлый вход был прерван.'; }
|
|
228
|
+
for (const a of db.accounts) if (a.provider === 'codex') background(refresh(a));
|
|
229
|
+
async function runAgentTurn(id, spec) {
|
|
230
|
+
const a = db.accounts.find(a=>a.id===id);
|
|
231
|
+
if (a && spec.expectedProvider !== undefined && a.provider !== spec.expectedProvider) throw new Error('Аккаунт не относится к выбранному провайдеру.');
|
|
232
|
+
if (!a || !a.enabled || a.status !== 'ready' || a.testPassed !== true) throw new Error('Аккаунт отключён или не прошёл проверку CLI.');
|
|
233
|
+
if (a.cooldown > Date.now() || remaining(a) === 0) throw new Error('Лимит аккаунта исчерпан. Дождитесь обновления лимитов; другой аккаунт автоматически не используется.');
|
|
234
|
+
const refreshing = active.get(a.id);
|
|
235
|
+
if (refreshing?.busy === 'refresh') await refreshing.task;
|
|
236
|
+
if (!a.enabled || a.status !== 'ready' || a.busy) throw new Error('Аккаунт отключён или занят. Дождитесь завершения текущей операции.');
|
|
237
|
+
const result = await start(a,'delegate',async signal => {
|
|
238
|
+
if (!await status(a,signal)) throw new Error(a.note);
|
|
239
|
+
const exe = (await availability())[a.provider];
|
|
240
|
+
if (!exe) throw new Error(`Не найден официальный CLI: ${names[a.provider]}.`);
|
|
241
|
+
let reply;
|
|
242
|
+
try {
|
|
243
|
+
reply = await (options.runAgent ?? runAgent)({ ...spec, provider:a.provider, exe, env:cliEnv(a.provider,dir(a)), signal,
|
|
244
|
+
onEvent:async event=>{
|
|
245
|
+
if (event.type === 'quota' && event.usage?.windows?.length) {
|
|
246
|
+
const previous = a.usage?.windows ?? [];
|
|
247
|
+
const windows = new Map(previous.filter(w=>Date.now()-(w.sampledAt ?? a.usage.updatedAt)<FRESH).map(w=>[w.label,w]));
|
|
248
|
+
for (const w of event.usage.windows) windows.set(w.label,{...w,sampledAt:event.usage.updatedAt});
|
|
249
|
+
a.usage = {...event.usage,windows:[...windows.values()]};
|
|
250
|
+
await persist();
|
|
251
|
+
return;
|
|
252
|
+
}
|
|
253
|
+
await spec.onEvent(event);
|
|
254
|
+
},
|
|
255
|
+
});
|
|
256
|
+
} catch (error) {
|
|
257
|
+
if (/rate.limit|usage limit|quota|hit your limit|too many requests|\b429\b/i.test(error.message)) a.cooldown = Date.now() + 5*60_000;
|
|
258
|
+
throw error;
|
|
259
|
+
}
|
|
260
|
+
a.lastUsed = Date.now();
|
|
261
|
+
a.note = 'Последняя задача агента завершена.';
|
|
262
|
+
await quota(a,signal);
|
|
263
|
+
return reply;
|
|
264
|
+
},spec.signal);
|
|
265
|
+
if (!result || result.ok === false) throw new Error(result?.error || 'CLI не завершил задачу.');
|
|
266
|
+
return result;
|
|
267
|
+
}
|
|
268
|
+
return {action, pick:provider=>{const a=pickAccount(db.accounts,provider);return a ? view(a) : undefined;}, modelAccounts, runAgentTurn,
|
|
269
|
+
hasEnabled:()=>db.accounts.some(a=>a.enabled && a.status==='ready'), async dispose(){clearInterval(interval);life.abort();await Promise.allSettled([...active.values()].map(w=>w.task)); await writes.catch(()=>{});} };
|
|
270
|
+
}
|
|
271
|
+
function cleanName(name) { return typeof name === 'string' ? name.replace(/[\x00-\x1f\x7f]/g,'').trim().slice(0,70) : ''; }
|
|
272
|
+
export function officialLoginUrl(provider, text) {
|
|
273
|
+
const hosts = provider === 'codex' ? ['auth.openai.com','login.openai.com'] : ['claude.ai','console.anthropic.com','platform.claude.com'];
|
|
274
|
+
for (const raw of text.match(/https:\/\/[^\s<>"\u001b]+/g) ?? []) {
|
|
275
|
+
try { const url = new URL(raw); if (hosts.includes(url.hostname) && !url.port && !url.username && !url.password && /oauth|authorize/.test(url.pathname) && raw.length < 8192) return url.href; } catch {}
|
|
276
|
+
}
|
|
277
|
+
}
|