@kealthas-dev/opencode-loki-query 0.0.0-stage → 1.1.23

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.
Files changed (3) hide show
  1. package/README.md +57 -2
  2. package/dist/cli.js +206 -0
  3. package/package.json +28 -4
package/README.md CHANGED
@@ -1,3 +1,58 @@
1
- # Temporary Holding Version
1
+ # loki
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Loki log queries for the agent as a command, `opencode-loki-query`, which reads a LogQL query from stdin, asks Loki (or Grafana's datasource proxy for it) and prints the result. Written in TypeScript (one file, `src/cli.ts`, no dependencies), compiled to `dist/`. There is no server to run. It is the same shape as [`oracle`](../oracle/README.md), whose README has the reasoning (why a command and not an MCP tool, why only a heredoc, why exit 0 or 1).
4
+
5
+ ## Usage
6
+
7
+ ```bash
8
+ opencode-loki-query --since 1h <<'LOGQL'
9
+ {app="api"} |= "error"
10
+ LOGQL
11
+
12
+ opencode-loki-query --start 2026-09-15T10:00:00+08:00 --end 2026-09-15T10:30:00+08:00 --limit 500 <<'LOGQL'
13
+ {app="api"}
14
+ LOGQL
15
+
16
+ opencode-loki-query --labels --since 24h
17
+ opencode-loki-query --values app --since 24h
18
+ opencode-loki-query --help
19
+ ```
20
+
21
+ The query is read from stdin, always: use a heredoc with a quoted delimiter so the shell leaves the quotes, backticks, `$` and backslashes of LogQL alone. The options are Loki's own query parameters, passed through unchanged, so Loki's own rules and defaults apply (a recent window, 100 lines, newest first):
22
+
23
+ | Option | Loki parameter |
24
+ |---|---|
25
+ | `--since 1h` | `since`: how far back from now |
26
+ | `--start`, `--end` | `start`, `end`: RFC3339 with an offset (`2026-09-15T10:00:00+08:00`) or a unix timestamp |
27
+ | `--limit N` | `limit`: most log lines to return |
28
+ | `--labels` | the label names, instead of a query |
29
+ | `--values LABEL` | the values of one label, instead of a query |
30
+
31
+ A query prints **one line of JSON per stream**, `{"stream":{...labels},"values":[["<ns timestamp>","<log line>"],...]}`; `--labels` and `--values` print one name or value per line. Only the result is printed, not Loki's envelope or its statistics block. An error from Loki is printed to stderr exactly as Loki gave it. Exit codes: `0` ok, `1` anything went wrong (stderr says what).
32
+
33
+ ## Configuration
34
+
35
+ Read from a file, not environment variables, at a fixed location under `$HOME/.config/kealthas-dev/opencode-loki-query/`: `config.json` by default, or `config-<name>.json` with `LOKI_CONFIG_ENV=<name>`. Only a short name is taken from the environment, never a path. The file is read on every run, so editing it needs nothing restarted.
36
+
37
+ ```json
38
+ {
39
+ "LOKI_BASE_URL": "http://192.168.1.100:3100",
40
+ "LOKI_USERNAME": "username",
41
+ "LOKI_PASSWORD": "password",
42
+ "LOKI_ORG_ID": "tenant-id",
43
+ "LOKI_VIA_GRAFANA": false,
44
+ "LOKI_GRAFANA_DATASOURCE_ID": "1"
45
+ }
46
+ ```
47
+
48
+ Only `LOKI_BASE_URL` (no trailing path) is required: Loki is commonly reachable without authentication on an internal LAN. `LOKI_USERNAME`/`LOKI_PASSWORD` are HTTP Basic auth and `LOKI_ORG_ID` the `X-Scope-OrgID` tenant header, each only if that instance needs it.
49
+
50
+ **If Loki has no directly reachable port and the only way in is Grafana's datasource proxy:** set `LOKI_BASE_URL` to Grafana's own URL, `LOKI_VIA_GRAFANA` to `true`, `LOKI_GRAFANA_DATASOURCE_ID` to the datasource's id (the number in `/connections/datasources/edit/...`'s API listing, `GET /api/datasources`; default `1`), and `LOKI_USERNAME`/`LOKI_PASSWORD` to a real Grafana user's Basic auth, not a Loki credential. Requests then go to `/api/datasources/proxy/<id>/loki/api/v1/...`. A Grafana that rejects the request answers with a redirect to its login page, not a 401; the command reports that redirect and what to check instead of following it. `config.example.json` shows the shape.
51
+
52
+ ## Installing it
53
+
54
+ Published as `@kealthas-dev/opencode-loki-query`. `npm install -g @kealthas-dev/opencode-loki-query` puts `opencode-loki-query` on `PATH`; then write the config file. See SETUP.md step 7.
55
+
56
+ ## Status
57
+
58
+ `loki.test.ts` runs against a real Loki instance in the docker sandbox (see `docker/notes.md`, "Loki test instance"), seeding lines through Loki's push API and running the built command the way an agent would: a query's streams and log lines, `--since`, `--start`/`--end` and `--limit`, a query with `$`, backticks and a backslash arriving untouched, `--labels` and `--values`, a malformed query's error passed through, a query matching nothing, usage errors, an unreachable Loki, and a missing or broken config file. The Grafana path (`LOKI_VIA_GRAFANA`, Basic auth, the org header, a redirect, an error body) is checked against a throwaway HTTP server standing in for Grafana, not against a real Grafana.
package/dist/cli.js ADDED
@@ -0,0 +1,206 @@
1
+ #!/usr/bin/env node
2
+ import { existsSync, readFileSync } from "node:fs";
3
+ import { homedir } from "node:os";
4
+ import { join } from "node:path";
5
+ // Exit codes: 0 ok, 1 anything went wrong (stderr says what).
6
+ const EXIT_FAILURE = 1;
7
+ const NAME = "opencode-loki-query";
8
+ const CONFIG_DIR = join(homedir(), ".config", "kealthas-dev", "opencode-loki-query");
9
+ // fetch() has no timeout by default - without this, a Loki/Grafana host
10
+ // that accepts the TCP connection but never responds (e.g. stuck behind a
11
+ // hung reverse proxy) leaves the request pending forever.
12
+ const REQUEST_TIMEOUT_MS = 30_000;
13
+ const HELP = `Usage: ${NAME} [options] <<'LOGQL'
14
+ <LogQL query>
15
+ LOGQL
16
+ ${NAME} --labels [options]
17
+ ${NAME} --values LABEL [options]
18
+
19
+ Runs one LogQL query, read from stdin, against the configured Loki and prints the result. A query prints one line of
20
+ JSON per stream (the entries are [nanosecond timestamp, log line] pairs); --labels and --values print one name or
21
+ value per line. Errors from Loki are printed exactly as Loki gave them.
22
+
23
+ The options are Loki's own query parameters, passed through unchanged:
24
+ --since DURATION how far back from now, e.g. 1h or 30m (Loki's default is a recent window)
25
+ --start TIME start of the range: RFC3339 with an offset (2026-09-15T10:00:00+08:00) or a unix timestamp
26
+ --end TIME end of the range, same forms
27
+ --limit N most log lines to return (Loki's default is 100)
28
+ --labels list the label names instead of running a query
29
+ --values LABEL list the values of one label instead of running a query
30
+ --help this text
31
+
32
+ The query goes in a heredoc with a quoted delimiter (<<'LOGQL', as above), so the shell leaves it alone: the quotes,
33
+ backticks, $ and backslashes of LogQL all reach Loki as written.
34
+
35
+ Exit codes: 0 ok, 1 failed; stderr says why.`;
36
+ function usageError(message) {
37
+ console.error(`${NAME}: ${message}\n\n${HELP}`);
38
+ process.exit(EXIT_FAILURE);
39
+ }
40
+ function parseArgs(argv) {
41
+ if (argv.includes("--help") || argv.includes("-h")) {
42
+ console.log(HELP);
43
+ process.exit(0);
44
+ }
45
+ const opts = { labels: false };
46
+ const valueOf = (i, flag) => {
47
+ const v = argv[i + 1];
48
+ if (v === undefined)
49
+ usageError(`${flag} needs a value`);
50
+ return v;
51
+ };
52
+ for (let i = 0; i < argv.length; i++) {
53
+ const arg = argv[i];
54
+ if (arg === "--labels")
55
+ opts.labels = true;
56
+ else if (arg === "--values")
57
+ opts.values = valueOf(i++, arg);
58
+ else if (arg === "--since")
59
+ opts.since = valueOf(i++, arg);
60
+ else if (arg === "--start")
61
+ opts.start = valueOf(i++, arg);
62
+ else if (arg === "--end")
63
+ opts.end = valueOf(i++, arg);
64
+ else if (arg === "--limit")
65
+ opts.limit = valueOf(i++, arg);
66
+ else
67
+ usageError(`unknown argument ${arg} (the query is read from stdin, not given as an argument)`);
68
+ }
69
+ if (opts.labels && opts.values !== undefined)
70
+ usageError("--labels and --values are separate modes");
71
+ return opts;
72
+ }
73
+ async function readStdin() {
74
+ const chunks = [];
75
+ for await (const chunk of process.stdin)
76
+ chunks.push(chunk);
77
+ return Buffer.concat(chunks).toString("utf8");
78
+ }
79
+ // The whole of stdin is the query. There is deliberately no argument form: LogQL is full of quotes, backticks and
80
+ // sometimes $, so any shell quoting of it is a way to get it wrong.
81
+ async function readQuery() {
82
+ if (process.stdin.isTTY)
83
+ usageError("no query: give it on stdin, with a heredoc");
84
+ const query = await readStdin();
85
+ if (query.trim() === "")
86
+ usageError("the query on stdin is empty");
87
+ return query;
88
+ }
89
+ const SAMPLE_CONFIG = {
90
+ LOKI_BASE_URL: "http://192.168.1.100:3100 (no trailing path)",
91
+ LOKI_USERNAME: "username (optional, HTTP basic auth)",
92
+ LOKI_PASSWORD: "password (optional)",
93
+ LOKI_ORG_ID: "tenant-id (optional, multi-tenant Loki / Grafana Cloud-style setups)",
94
+ LOKI_VIA_GRAFANA: "true (optional - set when Loki is only reachable through Grafana's own datasource proxy, not directly; LOKI_BASE_URL becomes Grafana's URL in that case)",
95
+ LOKI_GRAFANA_DATASOURCE_ID: "1 (optional, only used when LOKI_VIA_GRAFANA is true - defaults to 1)",
96
+ };
97
+ // config.json by default, config-<name>.json when LOKI_CONFIG_ENV is set. Read on every run, so editing it
98
+ // needs nothing restarted. Only a short name is taken from the environment, never a path.
99
+ // Only LOKI_BASE_URL is required - Loki is commonly reachable unauthenticated on an internal LAN.
100
+ function loadConfig() {
101
+ const envName = process.env.LOKI_CONFIG_ENV;
102
+ const path = join(CONFIG_DIR, envName ? `config-${envName}.json` : "config.json");
103
+ const sample = `Expected Loki config file at: ${path}\n${JSON.stringify(SAMPLE_CONFIG, null, 2)}`;
104
+ if (!existsSync(path))
105
+ throw new Error(`Loki config file not found.\n${sample}`);
106
+ try {
107
+ const raw = JSON.parse(readFileSync(path, "utf8"));
108
+ if (!raw.LOKI_BASE_URL)
109
+ throw new Error("missing required key LOKI_BASE_URL");
110
+ return {
111
+ baseUrl: raw.LOKI_BASE_URL,
112
+ username: raw.LOKI_USERNAME,
113
+ password: raw.LOKI_PASSWORD,
114
+ orgId: raw.LOKI_ORG_ID,
115
+ viaGrafana: raw.LOKI_VIA_GRAFANA === true,
116
+ grafanaDatasourceId: raw.LOKI_GRAFANA_DATASOURCE_ID !== undefined ? String(raw.LOKI_GRAFANA_DATASOURCE_ID) : "1",
117
+ };
118
+ }
119
+ catch (err) {
120
+ throw new Error(`Failed to load Loki config from ${path}: ${err.message}\n${sample}`);
121
+ }
122
+ }
123
+ async function main() {
124
+ const opts = parseArgs(process.argv.slice(2));
125
+ let path;
126
+ const params = new URLSearchParams();
127
+ if (opts.labels)
128
+ path = "/loki/api/v1/labels";
129
+ else if (opts.values !== undefined)
130
+ path = `/loki/api/v1/label/${encodeURIComponent(opts.values)}/values`;
131
+ else {
132
+ path = "/loki/api/v1/query_range";
133
+ params.set("query", await readQuery());
134
+ if (opts.limit !== undefined)
135
+ params.set("limit", opts.limit);
136
+ }
137
+ for (const key of ["since", "start", "end"]) {
138
+ if (opts[key] !== undefined)
139
+ params.set(key, opts[key]);
140
+ }
141
+ let config;
142
+ try {
143
+ config = loadConfig();
144
+ }
145
+ catch (err) {
146
+ console.error(`${NAME}: ${err.message}`);
147
+ return EXIT_FAILURE;
148
+ }
149
+ const effectivePath = config.viaGrafana ? `/api/datasources/proxy/${config.grafanaDatasourceId}${path}` : path;
150
+ const url = new URL(effectivePath, config.baseUrl);
151
+ url.search = params.toString();
152
+ const headers = {};
153
+ if (config.username || config.password) {
154
+ headers.Authorization = `Basic ${Buffer.from(`${config.username ?? ""}:${config.password ?? ""}`).toString("base64")}`;
155
+ }
156
+ if (config.orgId)
157
+ headers["X-Scope-OrgID"] = config.orgId;
158
+ let response;
159
+ try {
160
+ // Manual redirect handling: a Grafana instance rejecting the request (missing/expired auth, or
161
+ // LOKI_VIA_GRAFANA off when it should be on) responds with a 302 to its own login page, not a 401. Node's
162
+ // fetch follows that by default, landing on the login page's HTML with a misleadingly successful 200.
163
+ response = await fetch(url, { headers, redirect: "manual", signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS) });
164
+ }
165
+ catch (err) {
166
+ console.error(err.message);
167
+ return EXIT_FAILURE;
168
+ }
169
+ if (response.status >= 300 && response.status < 400) {
170
+ const location = response.headers.get("location") ?? "(no Location header)";
171
+ const hint = config.viaGrafana
172
+ ? "check LOKI_USERNAME/LOKI_PASSWORD (must be a real Grafana user's Basic Auth) and LOKI_GRAFANA_DATASOURCE_ID"
173
+ : "if this Loki is only reachable through Grafana's datasource proxy, set LOKI_VIA_GRAFANA: true (see README's Configuration section)";
174
+ console.error(`${NAME}: the request was redirected (${response.status}) to ${location} instead of returning data - ${hint}.`);
175
+ return EXIT_FAILURE;
176
+ }
177
+ // Text first, not response.json() - Loki's error responses aren't guaranteed to be JSON.
178
+ const text = await response.text();
179
+ if (!response.ok) {
180
+ console.error(text.trim() || `HTTP ${response.status} ${response.statusText}`); // Loki's own words
181
+ return EXIT_FAILURE;
182
+ }
183
+ // Only the result is printed: the envelope and the statistics block (a few KB per query) are not data.
184
+ const data = (text ? JSON.parse(text) : null)?.data;
185
+ const lines = Array.isArray(data) ? data : data?.result;
186
+ if (Array.isArray(lines)) {
187
+ for (const item of lines)
188
+ console.log(typeof item === "string" ? item : JSON.stringify(item));
189
+ }
190
+ else {
191
+ console.log(JSON.stringify(lines ?? data ?? null));
192
+ }
193
+ return 0;
194
+ }
195
+ // `... | head` closes the pipe early; that is not an error.
196
+ process.stdout.on("error", (err) => {
197
+ if (err.code === "EPIPE")
198
+ process.exit(0);
199
+ throw err;
200
+ });
201
+ main().then((code) => {
202
+ process.exitCode = code;
203
+ }, (err) => {
204
+ console.error(`${NAME}: ${err.message}`);
205
+ process.exitCode = EXIT_FAILURE;
206
+ });
package/package.json CHANGED
@@ -1,6 +1,30 @@
1
1
  {
2
2
  "name": "@kealthas-dev/opencode-loki-query",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.1.23",
4
+ "type": "module",
5
+ "description": "Loki log queries for the agent as a command, `opencode-loki-query`, reading the LogQL from stdin and connecting straight to Loki (or Grafana's datasource proxy) - see README.md for the design and the config.json-driven config",
6
+ "main": "dist/cli.js",
7
+ "bin": {
8
+ "opencode-loki-query": "dist/cli.js"
9
+ },
10
+ "files": [
11
+ "dist"
12
+ ],
13
+ "publishConfig": {
14
+ "access": "public"
15
+ },
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "https://github.com/Keal-thas/opencode-toolkit.git",
19
+ "directory": "cli/loki"
20
+ },
21
+ "scripts": {
22
+ "build": "tsc",
23
+ "test": "tsx --test loki.test.ts"
24
+ },
25
+ "devDependencies": {
26
+ "@types/node": "^22.0.0",
27
+ "tsx": "^4.19.0",
28
+ "typescript": "^5.6.0"
29
+ }
30
+ }