@coda-console/grok 1.8.0 → 1.8.2
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/agent/entry.mjs +20 -2
- package/agent/exit.mjs +12 -0
- package/agent/usage.mjs +24 -0
- package/package.json +1 -1
package/agent/entry.mjs
CHANGED
|
@@ -3,18 +3,23 @@
|
|
|
3
3
|
// Grok's questions are asked of Coda as ACP forms (questions.mjs). Grok gives one up (its timeout, a cancelled turn)
|
|
4
4
|
// by ending the tool call alone, so that end withdraws the form. Its context compactions, auto or a /compact of the user's, are
|
|
5
5
|
// told as `_x.ai/session_notification` updates, which are also told to Coda as `compaction_update` (docs/agent-protocol.md).
|
|
6
|
+
// The prompt's usage Grok tells in `_meta.usage` is also told as the response's `usage` (usage.mjs).
|
|
6
7
|
// Grok's ACP has no session/delete, so the entry declares it and answers it with `grok sessions delete`
|
|
7
8
|
// (delete.mjs; checked on 1.0.77): Coda's probes (session/new, then gone) leave no empty sessions in Grok's history.
|
|
8
9
|
import { spawn } from 'node:child_process';
|
|
9
10
|
import { randomUUID } from 'node:crypto';
|
|
10
11
|
import { grokBinary } from '../scripts/ask.mjs';
|
|
11
12
|
import { deleteSession } from './delete.mjs';
|
|
13
|
+
import { describeExit, endedError } from './exit.mjs';
|
|
12
14
|
import { ASK, questionForm } from './questions.mjs';
|
|
15
|
+
import { promptUsage } from './usage.mjs';
|
|
13
16
|
|
|
14
17
|
const modes = [{ id: 'auto', name: '自动审批', _meta: { coda: { shortName: '自动审批' } } },
|
|
15
18
|
{ id: 'always-approve', name: '全部放行', _meta: { coda: { shortName: '全部放行' } } }];
|
|
16
19
|
const binary = grokBinary() ?? 'grok';
|
|
17
|
-
const grok = spawn(binary, ['agent', '--no-leader', 'stdio'], { stdio: ['pipe', 'pipe', '
|
|
20
|
+
const grok = spawn(binary, ['agent', '--no-leader', 'stdio'], { stdio: ['pipe', 'pipe', 'pipe'] });
|
|
21
|
+
let stderr = '';
|
|
22
|
+
grok.stderr.on('data', chunk => { process.stderr.write(chunk); stderr = (stderr + chunk).slice(-2048); });
|
|
18
23
|
const send = (stream, message) => stream.write(`${JSON.stringify(message)}\n`);
|
|
19
24
|
const say = message => send(process.stdout, { jsonrpc: '2.0', ...message });
|
|
20
25
|
const pending = new Map();
|
|
@@ -91,6 +96,9 @@ read(grok.stdout, message => {
|
|
|
91
96
|
if (message.result && request.method === 'initialize') {
|
|
92
97
|
const capabilities = message.result.agentCapabilities ??= {};
|
|
93
98
|
capabilities.sessionCapabilities = { ...capabilities.sessionCapabilities, delete: {} };
|
|
99
|
+
} else if (message.result && request.method === 'session/prompt') {
|
|
100
|
+
const usage = promptUsage(message.result);
|
|
101
|
+
if (usage) message.result.usage = usage;
|
|
94
102
|
} else if (message.result && request.method !== 'session/prompt') {
|
|
95
103
|
sessionId = message.result.sessionId ?? request.params.sessionId;
|
|
96
104
|
mode = request.params?._meta?.yoloMode ? 'always-approve' : request.params?._meta?.autoMode ? 'auto' : '';
|
|
@@ -112,6 +120,16 @@ const stop = () => {
|
|
|
112
120
|
};
|
|
113
121
|
grok.stdin.on('error', () => {});
|
|
114
122
|
grok.on('error', () => process.exit(1));
|
|
115
|
-
|
|
123
|
+
// Grok dying on its own: the log and the prompts still waiting say how (exit.mjs).
|
|
124
|
+
grok.on('close', (code, signal) => {
|
|
125
|
+
const waiting = [...pending].filter(([, request]) => request.method === 'session/prompt');
|
|
126
|
+
if (!stopping && (code !== 0 || waiting.length)) {
|
|
127
|
+
const message = describeExit({ code, signal, stderr });
|
|
128
|
+
process.stderr.write(`${message}\n`);
|
|
129
|
+
for (const [id] of waiting) say({ id, error: endedError(message) });
|
|
130
|
+
}
|
|
131
|
+
// What was said reaches Coda before this process ends.
|
|
132
|
+
process.stdout.write('', () => process.exit(stopping ? 0 : code ?? 1));
|
|
133
|
+
});
|
|
116
134
|
process.stdin.on('end', stop);
|
|
117
135
|
for (const signal of ['SIGTERM', 'SIGINT', 'SIGHUP']) process.once(signal, stop);
|
package/agent/exit.mjs
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
// How `grok agent` ended, as the plugin's log and the turns it leaves waiting say it: its exit code or the signal that killed it,
|
|
2
|
+
// and the last lines it wrote to stderr. Told when the process ends on its own with a prompt unanswered, or with a non-zero exit code or a signal.
|
|
3
|
+
export function describeExit({ code, signal, stderr }) {
|
|
4
|
+
const tail = stderr.trim().split('\n').slice(-5).join('\n').slice(-1000);
|
|
5
|
+
return `Grok 进程意外退出(${signal ? `被信号 ${signal} 终止` : `退出码 ${code}`})${tail ? `,stderr 末尾:\n${tail}` : ''}`;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
// The error that ends a prompt as the process ends (docs/agent-protocol.md「原生会话已结束」): the category tells Coda the native
|
|
9
|
+
// session is over, not that the service failed. `input` is not written: nothing the
|
|
10
|
+
// process said proves this prompt was read, and Coda then resumes by checking first, with the whole original input.
|
|
11
|
+
export const endedError = message => ({ code: -32603, message,
|
|
12
|
+
data: { _meta: { coda: { failure: { kind: 'session_ended' } } } } });
|
package/agent/usage.mjs
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
// What a prompt used, as `PromptResponse.usage` says it (Coda's per-turn token collection): this turn's increment, `inputTokens` the
|
|
2
|
+
// uncached input, the cache reads and writes beside it. Grok (ACP, checked on 1.0.77) says it in the response's `_meta.usage` instead,
|
|
3
|
+
// per turn, with its `inputTokens` counting the cached tokens too: those are taken out of it. `_meta` stays as Grok sent it (Coda
|
|
4
|
+
// does not read it; other ACP clients may), and a response that already has a `usage` of its own keeps it.
|
|
5
|
+
const count = value => Number.isSafeInteger(value) && value >= 0 ? value : null;
|
|
6
|
+
|
|
7
|
+
// The `usage` to add to a successful prompt response `result`, or null where there is none to add.
|
|
8
|
+
export function promptUsage(result) {
|
|
9
|
+
if (!result || typeof result !== 'object' || Array.isArray(result) || (result.usage !== undefined && result.usage !== null)) return null;
|
|
10
|
+
const raw = result._meta?.usage;
|
|
11
|
+
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
|
|
12
|
+
const input = count(raw.inputTokens), output = count(raw.outputTokens), read = count(raw.cachedReadTokens);
|
|
13
|
+
const write = count(raw.cachedWriteTokens) ?? count(raw.cacheCreationTokens);
|
|
14
|
+
if (input === null && output === null && read === null && write === null) return null;
|
|
15
|
+
const uncached = input === null ? null : Math.max(0, input - (read ?? 0) - (write ?? 0));
|
|
16
|
+
return {
|
|
17
|
+
// The sum ACP's own Usage asks for, where the input and output are both there to make it.
|
|
18
|
+
...(uncached !== null && output !== null ? { totalTokens: uncached + output + (read ?? 0) + (write ?? 0) } : {}),
|
|
19
|
+
...(uncached === null ? {} : { inputTokens: uncached }),
|
|
20
|
+
...(output === null ? {} : { outputTokens: output }),
|
|
21
|
+
...(read === null ? {} : { cachedReadTokens: read }),
|
|
22
|
+
...(write === null ? {} : { cachedWriteTokens: write }),
|
|
23
|
+
};
|
|
24
|
+
}
|