@coda-console/grok 1.5.0 → 1.6.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/README.md +3 -1
- package/agent/entry.mjs +13 -17
- package/package.json +3 -3
- package/scripts/quota.mjs +10 -10
- package/scripts/resources.mjs +11 -0
- package/scripts/setup.mjs +2 -2
- package/agent/instructions.mjs +0 -68
- package/scripts/panel.mjs +0 -11
package/README.md
CHANGED
package/agent/entry.mjs
CHANGED
|
@@ -1,10 +1,9 @@
|
|
|
1
1
|
// Grok 1.0.52 reports no ACP modes. Translate set_mode to the notification its own UI sends; everything else passes
|
|
2
|
-
// through. No selected mode (the empty currentModeId) leaves the machine's configuration in charge, as before.
|
|
3
|
-
//
|
|
4
|
-
//
|
|
2
|
+
// through. No selected mode (the empty currentModeId) leaves the machine's configuration in charge, as before.
|
|
3
|
+
// Grok's questions are asked of Coda as ACP forms (questions.mjs). Grok gives one up (its timeout, a cancelled turn)
|
|
4
|
+
// by ending the tool call alone, so that end withdraws the form.
|
|
5
5
|
import { spawn } from 'node:child_process';
|
|
6
6
|
import { grokBinary } from '../scripts/ask.mjs';
|
|
7
|
-
import { SessionInstructions } from './instructions.mjs';
|
|
8
7
|
import { ASK, questionForm } from './questions.mjs';
|
|
9
8
|
|
|
10
9
|
const modes = [{ id: 'auto', name: '自动审批', _meta: { coda: { shortName: '自动审批' } } },
|
|
@@ -13,7 +12,6 @@ const grok = spawn(grokBinary() ?? 'grok', ['agent', '--no-leader', 'stdio'], {
|
|
|
13
12
|
const send = (stream, message) => stream.write(`${JSON.stringify(message)}\n`);
|
|
14
13
|
const say = message => send(process.stdout, { jsonrpc: '2.0', ...message });
|
|
15
14
|
const pending = new Map();
|
|
16
|
-
const instructions = new SessionInstructions();
|
|
17
15
|
// The forms asked of Coda, by their id: Grok's request they answer, its tool call, and how the answer is given back.
|
|
18
16
|
const questions = new Map();
|
|
19
17
|
let sessionId, mode = '', stopping = false, asked = 0;
|
|
@@ -30,14 +28,12 @@ function read(stream, receive) {
|
|
|
30
28
|
};
|
|
31
29
|
stream.setEncoding('utf8').on('data', take).on('end', () => take('\n'));
|
|
32
30
|
}
|
|
33
|
-
read(process.stdin,
|
|
34
|
-
const question = !
|
|
31
|
+
read(process.stdin, message => {
|
|
32
|
+
const question = !message.method && questions.get(message.id);
|
|
35
33
|
if (question) {
|
|
36
|
-
questions.delete(
|
|
37
|
-
send(grok.stdin, { jsonrpc: '2.0', id: question.id, result: question.answer(
|
|
34
|
+
questions.delete(message.id);
|
|
35
|
+
send(grok.stdin, { jsonrpc: '2.0', id: question.id, result: question.answer(message.result) }); return;
|
|
38
36
|
}
|
|
39
|
-
const { agent: message, coda } = instructions.fromCoda(said);
|
|
40
|
-
if (coda) { say(coda); return; }
|
|
41
37
|
if (message.method === 'session/set_mode' && 'id' in message) {
|
|
42
38
|
const chosen = message.params?.modeId;
|
|
43
39
|
const error = !sessionId || message.params?.sessionId !== sessionId ? 'Grok 会话不存在'
|
|
@@ -54,19 +50,19 @@ read(process.stdin, said => {
|
|
|
54
50
|
if ('id' in message && ['session/new', 'session/load', 'session/prompt'].includes(message.method)) pending.set(message.id, message);
|
|
55
51
|
send(grok.stdin, message);
|
|
56
52
|
});
|
|
57
|
-
read(grok.stdout,
|
|
58
|
-
if (
|
|
59
|
-
const id = `grok-ask-${++asked}`, { params, answer } = questionForm(
|
|
60
|
-
questions.set(id, { id:
|
|
53
|
+
read(grok.stdout, message => {
|
|
54
|
+
if (message.method === ASK && 'id' in message) {
|
|
55
|
+
const id = `grok-ask-${++asked}`, { params, answer } = questionForm(message.params ?? {});
|
|
56
|
+
questions.set(id, { id: message.id, toolCallId: params.toolCallId, answer });
|
|
61
57
|
say({ id, method: 'elicitation/create', params }); return;
|
|
62
58
|
}
|
|
63
|
-
const update =
|
|
59
|
+
const update = message.method === 'session/update' ? message.params?.update : null;
|
|
64
60
|
if (update?.sessionUpdate === 'tool_call_update' && ['completed', 'failed'].includes(update.status)) {
|
|
65
61
|
for (const [id, question] of questions) if (question.toolCallId === update.toolCallId) {
|
|
66
62
|
questions.delete(id); say({ method: '$/cancel_request', params: { requestId: id } });
|
|
67
63
|
}
|
|
68
64
|
}
|
|
69
|
-
const
|
|
65
|
+
const request = !message.method && pending.get(message.id);
|
|
70
66
|
if (request) {
|
|
71
67
|
pending.delete(message.id);
|
|
72
68
|
if (message.result && request.method !== 'session/prompt') {
|
package/package.json
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
"id": "grok",
|
|
4
4
|
"displayName": "Grok",
|
|
5
5
|
"description": "用 Grok CLI 跑会话",
|
|
6
|
-
"version": "1.
|
|
6
|
+
"version": "1.6.1",
|
|
7
7
|
"categories": [
|
|
8
8
|
"Agent"
|
|
9
9
|
],
|
|
@@ -31,11 +31,11 @@
|
|
|
31
31
|
"setupHint": "请在「资源」里为运行机添加 Grok。"
|
|
32
32
|
}
|
|
33
33
|
],
|
|
34
|
-
"
|
|
34
|
+
"resources": [
|
|
35
35
|
{
|
|
36
36
|
"id": "account",
|
|
37
37
|
"title": "Grok",
|
|
38
|
-
"command": "node \"$CODA_PLUGIN_PATH/scripts/
|
|
38
|
+
"command": "node \"$CODA_PLUGIN_PATH/scripts/resources.mjs\"",
|
|
39
39
|
"maxAge": "PT5M",
|
|
40
40
|
"signIn": {
|
|
41
41
|
"command": "g=\"$HOME/.grok/bin/grok\"; [ -x \"$g\" ] || g=grok; BROWSER=/usr/bin/true NO_COLOR=1 exec \"$g\" login --device-auth",
|
package/scripts/quota.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { createHash } from 'node:crypto';
|
|
2
2
|
|
|
3
|
-
// What the「Grok」
|
|
3
|
+
// What the「Grok」resource type shows (docs/plugins.md「内置插件:Grok」): who is signed in and the plan's coding credits, as the
|
|
4
4
|
// CLI itself answers them (`_x.ai/auth/check_subscription`, `_x.ai/auth/info`, `_x.ai/billing`: what its `/usage` reads).
|
|
5
5
|
const line = (value, max = 80) => typeof value === 'string' ? [...value.replace(/\s+/g, ' ').trim()].slice(0, max).join('') : '';
|
|
6
6
|
const instant = value => typeof value === 'string' && Number.isFinite(Date.parse(value)) ? new Date(value).toISOString() : null;
|
|
@@ -25,22 +25,22 @@ export function windows(document) {
|
|
|
25
25
|
const used = typeof config.creditUsagePercent === 'number' && Number.isFinite(config.creditUsagePercent) ? Math.min(100, Math.max(0, config.creditUsagePercent))
|
|
26
26
|
: limit > 0 ? Math.min(100, cents(config.used) / limit * 100) : 0;
|
|
27
27
|
const type = config.currentPeriod?.type, left = Math.round(100 - used), resets = instant(config.currentPeriod?.end ?? config.billingPeriodEnd);
|
|
28
|
-
const meters = [{
|
|
29
|
-
value: `剩余 ${left}%`, fraction: left / 100, ...(resets ? { time: resets
|
|
28
|
+
const meters = [{ label: type === 'USAGE_PERIOD_TYPE_WEEKLY' ? '7 天' : type === 'USAGE_PERIOD_TYPE_MONTHLY' ? '月度' : '额度',
|
|
29
|
+
value: `剩余 ${left}%`, fraction: left / 100, ...(resets ? { time: resets } : {}) }];
|
|
30
30
|
// A zero amount still arrives as `{}`; the older shape leaves on-demand spending out, and it is what went past the allowance.
|
|
31
31
|
const cap = cents(config.onDemandCap);
|
|
32
32
|
const onDemand = config.onDemandUsed != null ? cents(config.onDemandUsed) : Math.max(0, cents(config.used) - limit);
|
|
33
33
|
if (cap > 0) {
|
|
34
34
|
const share = Math.round(Math.max(0, cap - onDemand) / cap * 100);
|
|
35
|
-
meters.push({
|
|
35
|
+
meters.push({ label: '按需用量', value: `剩余 ${share}%`, fraction: share / 100 });
|
|
36
36
|
}
|
|
37
37
|
return meters;
|
|
38
38
|
}
|
|
39
|
-
// The
|
|
40
|
-
export function
|
|
39
|
+
// The resources from what the CLI answered: the login, its name and its credits; none when no one is signed in.
|
|
40
|
+
export function resources([subscription, info, billing]) {
|
|
41
41
|
const who = account(subscription, info);
|
|
42
|
-
if (!who) return {
|
|
43
|
-
const
|
|
44
|
-
return {
|
|
45
|
-
|
|
42
|
+
if (!who) return { resources: [] };
|
|
43
|
+
const values = windows(billing);
|
|
44
|
+
return { resources: [{ name: who.name || 'Grok', ...(who.id ? { identity: `grok:${who.id}` } : {}), values,
|
|
45
|
+
...(values.length ? {} : { error: '暂时无法获取额度:Grok 没有给出额度' }) }] };
|
|
46
46
|
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
// The「Grok」resources, printed once as `{ resources }`. No login file here shows nothing (the type is then offered under
|
|
2
|
+
// 「添加资源」); a CLI that cannot be asked fails the reading, which keeps the last one shown.
|
|
3
|
+
import { statSync } from 'node:fs';
|
|
4
|
+
import { join } from 'node:path';
|
|
5
|
+
import { grokAsk, grokHome } from './ask.mjs';
|
|
6
|
+
import { resources } from './quota.mjs';
|
|
7
|
+
|
|
8
|
+
try { statSync(join(grokHome(), 'auth.json')); }
|
|
9
|
+
catch (error) { if (error.code === 'ENOENT') { console.log('{"resources":[]}'); process.exit(0); } console.error(`读不了 Grok 的登录:${error.code}`); process.exit(1); }
|
|
10
|
+
try { console.log(JSON.stringify(resources(await grokAsk(['_x.ai/auth/check_subscription', '_x.ai/auth/info', '_x.ai/billing'])))); }
|
|
11
|
+
catch (error) { console.error(error.message); process.exit(1); }
|
package/scripts/setup.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// The plugin's setup (`contributes.setup`), which Coda runs on each machine when the user installs or updates the plugin: it
|
|
2
2
|
// ends well once the machine can run the agent. Without a Grok CLI that runs, or with one older than MINIMUM (the CLI whose
|
|
3
3
|
// `agent --no-leader stdio` and `_x.ai/yolo_mode_changed` the agent entry was checked against), Grok's own installer puts
|
|
4
|
-
// the latest in ~/.grok/bin, where the agent looks first, as the「Grok」
|
|
4
|
+
// the latest in ~/.grok/bin, where the agent looks first, as the「Grok」type's install does; a newer one is kept. Why the
|
|
5
5
|
// machine is not ready is said in one line on standard error.
|
|
6
6
|
import { spawnSync } from 'node:child_process';
|
|
7
7
|
import { realpathSync } from 'node:fs';
|
|
@@ -35,7 +35,7 @@ if (process.argv[1] && realpathSync(process.argv[1]) === realpathSync(fileURLToP
|
|
|
35
35
|
const before = needed(grokBinary());
|
|
36
36
|
if (before.action !== 'none') {
|
|
37
37
|
// What the installer prints goes to standard error with the rest of its story.
|
|
38
|
-
// As the
|
|
38
|
+
// As the type's `install`: without SHELL it leaves the shell's configuration alone.
|
|
39
39
|
const installed = spawnSync('bash', ['-c', 'set -o pipefail; curl -fsSL https://x.ai/cli/install.sh | bash'], { stdio: ['ignore', 2, 2],
|
|
40
40
|
env: { ...process.env, SHELL: '', PATH: `${join(homedir(), '.grok/bin')}:${process.env.PATH ?? ''}` } });
|
|
41
41
|
if (installed.status !== 0) { console.error(`${before.reason},安装失败(退出码 ${installed.status ?? installed.signal})`); process.exit(1); }
|
package/agent/instructions.mjs
DELETED
|
@@ -1,68 +0,0 @@
|
|
|
1
|
-
// Coda's session instructions (docs/agent-protocol.md「会话指令」) for an agent whose own ACP does not take `systemPrompt`: the
|
|
2
|
-
// entry declares that it does, keeps the parameter from the agent, and puts the text in front of the first prompt of a
|
|
3
|
-
// session the agent opened new, as a part of its own; a session it loaded has had them. A slash command is the agent's to
|
|
4
|
-
// read as one: the instructions wait for the next prompt. Kept the same in every plugin that relays a CLI's ACP.
|
|
5
|
-
const record = value => value && typeof value === 'object' && !Array.isArray(value);
|
|
6
|
-
|
|
7
|
-
// ACP's `systemPrompt`: its text, '' when there is none; throws on anything but text appended to the agent's own.
|
|
8
|
-
export function sessionInstructions(systemPrompt) {
|
|
9
|
-
if (systemPrompt === undefined || systemPrompt === null) return '';
|
|
10
|
-
if (systemPrompt.mode !== 'append') throw new Error('会话指令只支持 append 模式');
|
|
11
|
-
const { content } = systemPrompt;
|
|
12
|
-
if (!Array.isArray(content) || content.some(block => block?.type !== 'text' || typeof block.text !== 'string')) throw new Error('会话指令只接受文本块');
|
|
13
|
-
return content.map(block => block.text).join('\n\n');
|
|
14
|
-
}
|
|
15
|
-
|
|
16
|
-
// The part in front of the user's input: delimited, and said to be the client's, not the user's.
|
|
17
|
-
const OPENING = '<coda-session-instructions>';
|
|
18
|
-
export const instructionsBlock = text => ({ type: 'text', text: `${OPENING}\n`
|
|
19
|
-
+ 'Instructions from Coda, the client this session runs in, for the whole session. They are not part of the user\'s message.\n\n'
|
|
20
|
-
+ `${text}\n</coda-session-instructions>\n` });
|
|
21
|
-
|
|
22
|
-
export class SessionInstructions {
|
|
23
|
-
// Coda's requests whose answers are read here, by id; the instructions of a session yet to have its first prompt.
|
|
24
|
-
constructor() { this.asked = new Map(); this.waiting = new Map(); }
|
|
25
|
-
// What Coda says: `agent`, what the agent is told, or `coda`, Coda's answer given here instead.
|
|
26
|
-
fromCoda(message) {
|
|
27
|
-
const { id, method, params } = message;
|
|
28
|
-
if (!record(params)) return { agent: message };
|
|
29
|
-
if (method === 'initialize' && id !== undefined) this.asked.set(id, { initialize: true });
|
|
30
|
-
if (method === 'session/new' || method === 'session/load') {
|
|
31
|
-
let text;
|
|
32
|
-
try { text = sessionInstructions(params.systemPrompt); }
|
|
33
|
-
catch (error) { return { coda: { jsonrpc: '2.0', id, error: { code: -32602, message: error.message } } }; }
|
|
34
|
-
const { systemPrompt, ...rest } = params;
|
|
35
|
-
if (method === 'session/new' && text && id !== undefined) this.asked.set(id, { text });
|
|
36
|
-
return { agent: { ...message, params: rest } };
|
|
37
|
-
}
|
|
38
|
-
if (method === 'session/prompt' && Array.isArray(params.prompt) && this.waiting.has(params.sessionId)) {
|
|
39
|
-
const first = params.prompt.find(block => block?.type === 'text');
|
|
40
|
-
if (typeof first?.text === 'string' && first.text.trimStart().startsWith('/')) return { agent: message };
|
|
41
|
-
const text = this.waiting.get(params.sessionId);
|
|
42
|
-
this.waiting.delete(params.sessionId);
|
|
43
|
-
return { agent: { ...message, params: { ...params, prompt: [instructionsBlock(text), ...params.prompt] } } };
|
|
44
|
-
}
|
|
45
|
-
return { agent: message };
|
|
46
|
-
}
|
|
47
|
-
// What the agent says, as said to Coda. A title the agent took from the first prompt's text begins with the instructions,
|
|
48
|
-
// not with what the user asked: it is left out, and the session keeps the title Coda gives it.
|
|
49
|
-
fromAgent(message) {
|
|
50
|
-
const update = message?.method === 'session/update' && record(message.params) ? message.params.update : null;
|
|
51
|
-
if (record(update) && update.sessionUpdate === 'session_info_update' && typeof update.title === 'string' && update.title.trimStart().startsWith(OPENING)) {
|
|
52
|
-
const { title, ...rest } = update;
|
|
53
|
-
return { ...message, params: { ...message.params, update: rest } };
|
|
54
|
-
}
|
|
55
|
-
if (!record(message) || !('id' in message) || 'method' in message) return message;
|
|
56
|
-
const asked = this.asked.get(message.id);
|
|
57
|
-
if (!asked) return message;
|
|
58
|
-
this.asked.delete(message.id);
|
|
59
|
-
if (!record(message.result)) return message;
|
|
60
|
-
if (asked.text) {
|
|
61
|
-
if (typeof message.result.sessionId === 'string') this.waiting.set(message.result.sessionId, asked.text);
|
|
62
|
-
return message;
|
|
63
|
-
}
|
|
64
|
-
const capabilities = record(message.result.agentCapabilities) ? message.result.agentCapabilities : {};
|
|
65
|
-
const sessions = record(capabilities.sessionCapabilities) ? capabilities.sessionCapabilities : {};
|
|
66
|
-
return { ...message, result: { ...message.result, agentCapabilities: { ...capabilities, sessionCapabilities: { ...sessions, systemPrompt: {} } } } };
|
|
67
|
-
}
|
|
68
|
-
}
|
package/scripts/panel.mjs
DELETED
|
@@ -1,11 +0,0 @@
|
|
|
1
|
-
// The「Grok」panel's reading, printed once as `{ items }`. No login file here shows nothing (the panel is then offered under
|
|
2
|
-
// 「添加资源」); a CLI that cannot be asked fails the reading, which keeps the last one shown.
|
|
3
|
-
import { statSync } from 'node:fs';
|
|
4
|
-
import { join } from 'node:path';
|
|
5
|
-
import { grokAsk, grokHome } from './ask.mjs';
|
|
6
|
-
import { panel } from './quota.mjs';
|
|
7
|
-
|
|
8
|
-
try { statSync(join(grokHome(), 'auth.json')); }
|
|
9
|
-
catch (error) { if (error.code === 'ENOENT') { console.log('{"items":[]}'); process.exit(0); } console.error(`读不了 Grok 的登录:${error.code}`); process.exit(1); }
|
|
10
|
-
try { console.log(JSON.stringify(panel(await grokAsk(['_x.ai/auth/check_subscription', '_x.ai/auth/info', '_x.ai/billing'])))); }
|
|
11
|
-
catch (error) { console.error(error.message); process.exit(1); }
|