@getyak/tormie 0.1.0-beta.1 → 0.3.0-beta.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 CHANGED
@@ -1,6 +1,6 @@
1
1
  # Tormie CLI Beta
2
2
 
3
- Tormie CLI reads and cites exact notes from your workspace. The package includes the `tormie` command and the local `tormie-mcp` server. It requires Node.js 22 or newer.
3
+ Tormie CLI reads and cites exact notes from your workspace. The package runs the platform-specific Rust `tormie` executable and includes a separate local `tormie-mcp` server. The npm launcher and MCP server require Node.js 22 or newer.
4
4
 
5
5
  ## Connect a terminal
6
6
 
Binary file
Binary file
Binary file
Binary file
package/mcp.mjs CHANGED
@@ -9,14 +9,15 @@ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"
9
9
  // packages/public-cli/package.json
10
10
  var package_default = {
11
11
  name: "@getyak/tormie",
12
- version: "0.1.0-beta.1",
12
+ version: "0.3.0-beta.1",
13
13
  description: "Read exact, citable Tormie notes from a terminal or local MCP host.",
14
14
  type: "module",
15
15
  bin: {
16
- tormie: "cli.mjs",
16
+ tormie: "run.mjs",
17
17
  "tormie-mcp": "mcp.mjs"
18
18
  },
19
- files: ["cli.mjs", "mcp.mjs"],
19
+ files: ["run.mjs", "mcp.mjs", "bin/"],
20
+ tormiePlatforms: ["darwin-arm64", "darwin-x64", "linux-arm64", "linux-x64"],
20
21
  engines: {
21
22
  node: ">=22"
22
23
  },
package/package.json CHANGED
@@ -1,13 +1,14 @@
1
1
  {
2
2
  "name": "@getyak/tormie",
3
- "version": "0.1.0-beta.1",
3
+ "version": "0.3.0-beta.1",
4
4
  "description": "Read exact, citable Tormie notes from a terminal or local MCP host.",
5
5
  "type": "module",
6
6
  "bin": {
7
- "tormie": "cli.mjs",
7
+ "tormie": "run.mjs",
8
8
  "tormie-mcp": "mcp.mjs"
9
9
  },
10
- "files": ["cli.mjs", "mcp.mjs"],
10
+ "files": ["run.mjs", "mcp.mjs", "bin/"],
11
+ "tormiePlatforms": ["darwin-arm64", "darwin-x64", "linux-arm64", "linux-x64"],
11
12
  "engines": {
12
13
  "node": ">=22"
13
14
  },
package/run.mjs ADDED
@@ -0,0 +1,50 @@
1
+ #!/usr/bin/env node
2
+ import { spawn } from 'node:child_process';
3
+ import { fileURLToPath } from 'node:url';
4
+
5
+ const target = `${process.platform}-${process.arch}`;
6
+ const filename = process.platform === 'win32' ? 'tormie.exe' : 'tormie';
7
+ const binary = fileURLToPath(new URL(`./bin/${target}/${filename}`, import.meta.url));
8
+ const mcp = fileURLToPath(new URL('./mcp.mjs', import.meta.url));
9
+ const entry = fileURLToPath(import.meta.url);
10
+ const args = process.argv.slice(2);
11
+ const token = process.env.TORMIE_TOKEN !== undefined || args.includes('--token-stdin');
12
+ const inherited = process.env.TORMIE_API_URL;
13
+ const deliberateOrigin = args.some((arg, index) =>
14
+ arg === '--base-url' && Boolean(args[index + 1]) || arg.startsWith('--base-url='));
15
+ const command = args[0] === '--json' ? args[1] : args[0];
16
+ const offline = command === undefined
17
+ || ['help', 'schema', 'doctor', 'mcp', 'setup', '--version', '-V', '--help', '-h'].includes(command);
18
+ const passwordLogin = args.includes('auth') && args.includes('login')
19
+ && args.some(arg => arg === '--email' || arg.startsWith('--email='));
20
+ if (passwordLogin && !deliberateOrigin && !offline) {
21
+ process.stderr.write(`${JSON.stringify({error: {
22
+ code: 'origin_required',
23
+ next_action: 'Pass --base-url with the service that should receive the password.',
24
+ }})}\n`);
25
+ process.exit(2);
26
+ }
27
+ if (!offline && token && inherited !== undefined && inherited !== 'https://api.tormie.com' && !deliberateOrigin) {
28
+ process.stderr.write(`${JSON.stringify({error: {
29
+ code: 'unsupported_origin',
30
+ next_action: 'Clear TORMIE_API_URL for production, or pass --base-url explicitly for the intended private service.',
31
+ }})}\n`);
32
+ process.exit(2);
33
+ }
34
+ const official = inherited === undefined && token && !deliberateOrigin;
35
+ const child = spawn(binary, args, {
36
+ env: { ...process.env, ...(official ? { TORMIE_API_URL: 'https://api.tormie.com' } : {}),
37
+ TORMIE_PACKAGED_MCP: mcp, TORMIE_PACKAGED_NODE: process.execPath, TORMIE_PACKAGED_ENTRY: entry },
38
+ stdio: 'inherit',
39
+ });
40
+ child.once('error', () => {
41
+ process.stderr.write(`${JSON.stringify({ error: {
42
+ code: 'native_binary_unavailable',
43
+ next_action: `Install a Tormie package containing the Rust executable for ${target}.`,
44
+ } })}\n`);
45
+ process.exitCode = 1;
46
+ });
47
+ child.once('exit', (code, signal) => {
48
+ if (signal && process.platform !== 'win32') process.kill(process.pid, signal);
49
+ else process.exitCode = code ?? 1;
50
+ });
package/cli.mjs DELETED
@@ -1,453 +0,0 @@
1
- #!/usr/bin/env node
2
-
3
- // packages/public-cli/cli.mjs
4
- import { execFile } from "node:child_process";
5
- import { constants } from "node:fs";
6
- import { access, realpath, stat } from "node:fs/promises";
7
- import { delimiter, resolve } from "node:path";
8
- import { fileURLToPath, pathToFileURL } from "node:url";
9
- import { promisify } from "node:util";
10
-
11
- // packages/public-cli/package.json
12
- var package_default = {
13
- name: "@getyak/tormie",
14
- version: "0.1.0-beta.1",
15
- description: "Read exact, citable Tormie notes from a terminal or local MCP host.",
16
- type: "module",
17
- bin: {
18
- tormie: "cli.mjs",
19
- "tormie-mcp": "mcp.mjs"
20
- },
21
- files: ["cli.mjs", "mcp.mjs"],
22
- engines: {
23
- node: ">=22"
24
- },
25
- homepage: "https://tormie.com/cli/",
26
- repository: {
27
- type: "git",
28
- url: "https://github.com/getyak/tormie.git",
29
- directory: "packages/public-cli"
30
- },
31
- publishConfig: {
32
- access: "public",
33
- tag: "beta"
34
- },
35
- dependencies: {
36
- "@modelcontextprotocol/sdk": "1.32.2",
37
- zod: "4.6.6"
38
- }
39
- };
40
-
41
- // packages/public-cli/knowledge.mjs
42
- import { z } from "zod";
43
-
44
- // packages/cli/client.mjs
45
- import { createHash, randomUUID } from "node:crypto";
46
- var ApiError = class extends Error {
47
- constructor(status, code) {
48
- super(`Tormie request failed (${status}; ${code}).`);
49
- this.status = status;
50
- this.code = code;
51
- }
52
- };
53
- function apiOrigin(value = process.env.TORMIE_API_URL ?? "http://127.0.0.1:4173") {
54
- const url = new URL(value);
55
- if (url.username || url.password || url.search || url.hash || !["http:", "https:"].includes(url.protocol)) throw new Error("Use an API origin without credentials or query parameters.");
56
- if (url.protocol !== "https:" && !["localhost", "127.0.0.1", "[::1]"].includes(url.hostname)) throw new Error("A remote API requires HTTPS.");
57
- if (!["", "/", "/api/v1", "/api/v1/"].includes(url.pathname)) throw new Error("Use the API origin or its /api/v1 base path.");
58
- return url.origin;
59
- }
60
- var TormieClient = class {
61
- constructor({ baseUrl, token = process.env.TORMIE_TOKEN, fetchImpl = fetch, timeoutMs = 6e4, expectedUserId } = {}) {
62
- this.origin = apiOrigin(baseUrl);
63
- this.token = token;
64
- this.fetch = fetchImpl;
65
- this.timeoutMs = timeoutMs;
66
- this.expectedUserId = expectedUserId;
67
- }
68
- async request(path, { method = "GET", body, binary, headers = {}, key } = {}) {
69
- if (!path.startsWith("/") || path.startsWith("//") || path.split("?")[0].split("/").some((segment) => [".", ".."].includes(decodeURIComponent(segment)))) throw new Error("Invalid API path.");
70
- if (key !== void 0 && (typeof key !== "string" || !/^[\x21-\x7e]{1,200}$/.test(key))) throw new ApiError(400, "invalid_idempotency_key");
71
- const actualHeaders = { Accept: "application/json", ...headers };
72
- if (this.expectedUserId) actualHeaders["X-Tormie-User-ID"] = this.expectedUserId;
73
- if (this.token) actualHeaders.Authorization = `Bearer ${this.token}`;
74
- if (body !== void 0) actualHeaders["Content-Type"] = "application/json";
75
- if (method !== "GET" && method !== "HEAD") actualHeaders["Idempotency-Key"] = key ?? randomUUID();
76
- let response;
77
- try {
78
- response = await this.fetch(`${this.origin}/api/v1${path}`, {
79
- method,
80
- headers: actualHeaders,
81
- body: binary ?? (body === void 0 ? void 0 : JSON.stringify(body)),
82
- ...binary ? { duplex: "half" } : {},
83
- redirect: "error",
84
- signal: AbortSignal.timeout(this.timeoutMs)
85
- });
86
- } catch {
87
- throw new ApiError(0, "connection_failed");
88
- }
89
- let data;
90
- try {
91
- data = await response.json();
92
- } catch {
93
- throw new ApiError(response.status, "invalid_response");
94
- }
95
- if (!response.ok) {
96
- const code = /^[a-z0-9_]{1,80}$/.test(data?.error?.code ?? "") ? data.error.code : "request_failed";
97
- throw new ApiError(response.status, code);
98
- }
99
- return data;
100
- }
101
- feedback(input, key, { sourceReadAllowed = false } = {}) {
102
- return this.request("/feedback", { method: "POST", body: input, key, headers: { "X-Tormie-Surface": "mcp", "X-Tormie-Feedback-Source-Read": sourceReadAllowed ? "yes" : "no" } });
103
- }
104
- config() {
105
- return this.request("/config");
106
- }
107
- connectionCatalog() {
108
- return this.request("/connection-tools/catalog");
109
- }
110
- connections(agent = "tormie", input = {}) {
111
- return this.request("/connection-tools?" + query({ agent_id: agent, ...input }));
112
- }
113
- proposeConnection(input, key) {
114
- return this.request("/connection-requests", { method: "POST", body: input, key });
115
- }
116
- connectionRequest(id) {
117
- return this.request("/connection-requests/" + encodeURIComponent(id));
118
- }
119
- proposeTool(input, key) {
120
- return this.request("/connection-tool-requests", { method: "POST", body: input, key });
121
- }
122
- session() {
123
- return this.request("/auth/session");
124
- }
125
- login(email, password) {
126
- return this.request("/auth/email/login", { method: "POST", body: { email, password, client: "cli" } });
127
- }
128
- notes({ q, limit = 60, cursor } = {}) {
129
- return this.request(`/records?${query({ q, limit, cursor })}`);
130
- }
131
- note(id) {
132
- return this.request(`/records/${encodeURIComponent(id)}`);
133
- }
134
- cardTools(agent = "tormie") {
135
- return this.request(`/agents/${encodeURIComponent(agent)}/card-tools`);
136
- }
137
- setCardTools(agent, input, key) {
138
- return this.request(`/agents/${encodeURIComponent(agent)}/card-tools`, { method: "PATCH", body: input, key });
139
- }
140
- callCardTool(name, args = {}, { scope: scope2, key, approved = false, agent } = {}) {
141
- return this.request(agent ? `/agents/${encodeURIComponent(agent)}/card-tools/call` : "/card-tools/call", { method: "POST", body: { name, arguments: args, ...scope2 === void 0 ? {} : { scope: scope2 }, ...approved ? { approved: true } : {} }, key });
142
- }
143
- createNote(input, key) {
144
- return this.request("/records", { method: "POST", body: { ...input, meta: { schema_version: 1, source: "cli", ...input.meta } }, key });
145
- }
146
- callConversationTool(name, args = {}, scopeCeiling) {
147
- return this.request("/conversation-tools/call", { method: "POST", body: { name, arguments: args, ...scopeCeiling ? { scope_ceiling: scopeCeiling } : {} } });
148
- }
149
- conversations() {
150
- return this.request("/conversations");
151
- }
152
- createConversation(title, key) {
153
- return this.request("/conversations", { method: "POST", body: { ...title ? { title } : {} }, key });
154
- }
155
- messages({ conversation_id, limit = 60, cursor, scope_ceiling, view } = {}) {
156
- return this.request(`/messages?${query({ conversation_id, limit, cursor, scope_ceiling, view })}`);
157
- }
158
- setMessageReaction(id, emoji, key) {
159
- return this.request(`/messages/${id}/reaction`, { method: "PUT", body: { emoji }, key });
160
- }
161
- createMessage(input, key) {
162
- return this.request("/messages", { method: "POST", body: { request_ai: false, ...input }, key });
163
- }
164
- agentRun(input, key) {
165
- return this.request("/agent/run", { method: "POST", body: input, key });
166
- }
167
- run(id) {
168
- return this.request(`/runs/${encodeURIComponent(id)}`);
169
- }
170
- sync({ cursor = "0", limit = 100 } = {}) {
171
- return this.request(`/sync?${query({ cursor, limit })}`);
172
- }
173
- };
174
- function query(object) {
175
- return new URLSearchParams(Object.entries(object).filter(([, value]) => value !== void 0 && value !== null).map(([key, value]) => [key, String(value)])).toString();
176
- }
177
-
178
- // packages/knowledge/card-schema.mjs
179
- var MAX_REFS = 20;
180
- var MAX_TEXT_POINTS = 2e4;
181
- var fields = /* @__PURE__ */ new Set(["captured_at", "created_at", "updated_at"]);
182
- var kinds = /* @__PURE__ */ new Set(["text", "audio", "image", "video", "file"]);
183
- var schemaRef = { type: "object", properties: { record_id: { type: "string" }, version: { type: "integer", minimum: 1 }, source_hash: { type: "string" }, coordinate: { enum: ["original_text", "derived_transcript"] } }, required: ["record_id", "version"], additionalProperties: false };
184
- var schemaRefs = { type: "array", items: schemaRef, maxItems: MAX_REFS };
185
- var dateBounds = { type: "object", description: "Absolute ISO timestamps with Z or an offset. gte is inclusive; lt is exclusive.", properties: { gte: { type: "string", format: "date-time" }, lt: { type: "string", format: "date-time" } }, additionalProperties: false, minProperties: 1 };
186
- var filterSchema = { type: "object", properties: {
187
- ...Object.fromEntries([...fields].map((field) => [field, dateBounds])),
188
- tags: { type: "array", items: { type: "string", maxLength: 200 }, maxItems: 20, description: "All specified tag paths must match; a parent includes descendants." },
189
- kinds: { type: "array", items: { enum: [...kinds] }, maxItems: 5 },
190
- timezone: { type: "string", maxLength: 100, description: "IANA timezone for interpreting/reporting calendar dates; absolute bounds retain their own offset." }
191
- }, additionalProperties: false };
192
- var chunkProperties = { offset: { type: "integer", minimum: 0, description: "Unicode codepoint offset into this exact saved text layer." }, length: { type: "integer", minimum: 1, maximum: MAX_TEXT_POINTS } };
193
- var metadataOnlySchema = { type: "boolean", description: "Return source metadata without any source text. Preserved in batch continuations." };
194
- var queryProperties = { query: { type: "string", maxLength: 500, description: "Keywords, not instructions. Omit for filter-only browsing. Example: Tormei or \u60F3\u6362\u5DE5\u4F5C." }, mode: { enum: ["auto", "literal", "fuzzy", "semantic", "hybrid"], description: "auto (default): literal, Chinese word segmentation and conservative Latin spelling tolerance. literal: exact normalized substrings, all words required. Semantic/hybrid report unavailable semantic retrieval and literal fallback." }, filters: filterSchema, sort: { enum: ["relevance", "captured_desc", "captured_asc"] }, limit: { type: "integer", minimum: 1, maximum: 20 }, cursor: { type: ["string", "null"] } };
195
- var definition = (name, description, properties, required = []) => ({ name, description, inputSchema: { type: "object", properties, required, additionalProperties: false } });
196
- var CARD_TOOL_NAMES = Object.freeze(["tormie_notes_search", "tormie_notes_read", "tormie_notes_on_date", "tormie_notes_terms", "tormie_notes_related", "tormie_groups_preview", "tormie_context_build", "tormie_collection_save", "tormie_notes_list", "tormie_eval", "tormie_notes_stats"]);
197
- var cardToolDefinitions = [
198
- definition(CARD_TOOL_NAMES[0], "Find authorized exact-version cards with multilingual lexical/spelling matching, strict tag/date filters, relevance sorting, source metadata, match evidence and executable read_args. Previews are partial evidence; follow next_cursor for more candidates. No semantic synonyms, model calls or attachment reads.", queryProperties),
199
- definition(CARD_TOOL_NAMES[1], "Read exact saved text and source metadata. Use record_id+version for one card, OR requests for up to 20 independently chunked reads. Every batch member is authorized before output. Use metadata_only to inspect context without text. Follow next_read, next_requests or ref+next_offset; omissions are explicit. Originals and derived_transcript stay separate; attachments are not read.", { ...schemaRef.properties, ...chunkProperties, metadata_only: metadataOnlySchema, requests: { type: "array", minItems: 1, maxItems: MAX_REFS, items: { ...schemaRef, properties: { ...schemaRef.properties, ...chunkProperties, metadata_only: metadataOnlySchema } } } }),
200
- definition(CARD_TOOL_NAMES[2], "Find captured, created or modified cards on inclusive calendar dates in an IANA timezone.", { ...queryProperties, date: { type: "string" }, start_date: { type: "string" }, end_date: { type: "string" }, timezone: { type: "string" }, field: { enum: [...fields] } }),
201
- definition(CARD_TOOL_NAMES[3], "Extract deterministic literal terms and exact source spans, without a model or stored index.", { refs: schemaRefs, max_terms: { type: "integer", minimum: 1, maximum: 20 }, language: { type: "string", maxLength: 40 } }, ["refs"]),
202
- definition(CARD_TOOL_NAMES[4], "Find lexical candidates from exact seeds and explicit query expansions. Similarity does not imply agreement.", { ...queryProperties, seeds: schemaRefs, expansions: { type: "array", items: { type: "string", maxLength: 100 }, maxItems: 10 } }, ["seeds"]),
203
- definition(CARD_TOOL_NAMES[5], "Validate a temporary Agent-proposed grouping. Titles and relationships remain inferred; originals are unchanged.", { candidates: schemaRefs, groups: { type: "array", maxItems: 10, items: { type: "object", properties: { title: { type: "string", maxLength: 160 }, members: schemaRefs, rationale: { type: "string", maxLength: 1e3 } }, required: ["title", "members"], additionalProperties: false } } }, ["candidates", "groups"]),
204
- definition(CARD_TOOL_NAMES[6], "Build a bounded transient pack of exact excerpts, prioritizing pinned sources and reporting omissions.", { task: { type: "string", maxLength: 1e3 }, refs: schemaRefs, pinned_refs: schemaRefs, groups: { type: "array", maxItems: 10 }, byte_budget: { type: "integer", minimum: 512, maximum: 32768 } }, ["refs"]),
205
- definition(CARD_TOOL_NAMES[7], "Save a reviewed derived collection with separate derivative permission, exact sources and revision protection.", { title: { type: "string", maxLength: 160 }, draft: { type: "object" }, reviewed: { const: true }, expected_revision: { type: "integer", minimum: 0 }, collection_id: { type: "string" } }, ["title", "draft", "reviewed", "expected_revision"]),
206
- definition(CARD_TOOL_NAMES[8], "List authorized notes using stable pages. Follow next_cursor to reach all granted notes; previews are not full reads and one page is not the whole library.", { filters: { type: "object" }, limit: queryProperties.limit, cursor: queryProperties.cursor }),
207
- definition(CARD_TOOL_NAMES[9], "Run a synchronous JavaScript function body with explicit return over exact admitted note snapshots. The immutable notes array contains {ref,text,captured_at,tags,kind}. No computer files, credentials, imports or network are available. Results are derived and coverage describes only the supplied batch, never the whole library.", { code: { type: "string", maxLength: 16384 }, refs: schemaRefs }, ["code", "refs"]),
208
- definition(CARD_TOOL_NAMES[10], "Count current visible notes within the granted scope using metadata only. Originals and transcripts count once; Trash and historical versions are excluded. Returns no source text or record IDs.", { filters: filterSchema })
209
- ];
210
-
211
- // packages/public-cli/knowledge.mjs
212
- var origin = "https://api.tormie.com";
213
- var developerUrl = "https://app.tormie.com/?settings=developer";
214
- var scope = "knowledge:read";
215
- var uuid = /^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i;
216
- var tokenFormat = /^tmk_[A-Za-z0-9_-]{43}$/;
217
- var actions = { search: "tormie_notes_search", read: "tormie_notes_read" };
218
- var PreviewError = class extends Error {
219
- constructor(code, nextAction, exitCode = 1) {
220
- super(nextAction);
221
- this.code = code;
222
- this.exitCode = exitCode;
223
- }
224
- };
225
- var invalid = (message) => new PreviewError("invalid_arguments", message, 2);
226
- function definition2(command) {
227
- return cardToolDefinitions.find((tool) => tool.name === actions[command]);
228
- }
229
- function describe(command) {
230
- const { name, description, inputSchema: inputSchema2 } = definition2(command);
231
- return { command, name, description, input_schema: inputSchema2, required_scope: scope };
232
- }
233
- function inputSchema(command) {
234
- const converted = z.fromJSONSchema(definition2(command).inputSchema);
235
- if (command !== "read") return converted;
236
- return converted.refine((input) => {
237
- if (input.requests === void 0) return uuid.test(input.record_id ?? "") && input.version !== void 0;
238
- return input.requests.length > 0 && input.requests.every((ref) => uuid.test(ref.record_id)) && ["record_id", "version", "source_hash", "coordinate", "offset", "length"].every((key) => input[key] === void 0);
239
- }, "Supply an exact record ID and version, or a nonempty batch of exact references.");
240
- }
241
- var guidance = {
242
- connection_failed: "Check your network connection to api.tormie.com and try again.",
243
- source_identity_mismatch: "Search again and use the exact source reference returned by Tormie.",
244
- not_found: "Run search again and select a currently available source.",
245
- record_not_found: "Run search again and select a currently available source.",
246
- user_context_mismatch: "Check the approved workspace UUID in your secret configuration.",
247
- user_context_required: "Set TORMIE_EXPECTED_USER_ID to the approved workspace UUID.",
248
- scope_denied: "Check the client grant in Tormie Web Settings \u2192 Developer access.",
249
- invalid_card_arguments: "Check the syntax with tormie schema search or tormie schema read."
250
- };
251
- function errorOutput(error) {
252
- if (error instanceof PreviewError) return { code: error.code, next_action: error.message };
253
- if (error instanceof ApiError) {
254
- if (error.status === 401) return { code: "grant_unavailable", next_action: "Check the token expiry or revocation in Tormie Web Settings \u2192 Developer access." };
255
- if (error.status === 404) return { code: error.code, next_action: guidance.not_found };
256
- if (error.status === 429) return { code: "rate_limited", next_action: "Wait before retrying the request." };
257
- if (Object.hasOwn(guidance, error.code)) return { code: error.code, next_action: guidance[error.code] };
258
- }
259
- return { code: "request_failed", next_action: "Run tormie doctor or check whether Tormie is available." };
260
- }
261
- function createKnowledgeClient(env = process.env, fetchImpl = fetch) {
262
- if (env.TORMIE_API_URL !== void 0 && env.TORMIE_API_URL !== origin) {
263
- throw new PreviewError("unsupported_origin", "Remove TORMIE_API_URL or set it to https://api.tormie.com.");
264
- }
265
- if (!tokenFormat.test(env.TORMIE_TOKEN ?? "")) {
266
- throw new PreviewError("grant_required", "Run tormie setup and configure a Developer access token in your host secret store.");
267
- }
268
- if (!uuid.test(env.TORMIE_EXPECTED_USER_ID ?? "")) {
269
- throw new PreviewError("workspace_required", "Set TORMIE_EXPECTED_USER_ID to the approved workspace UUID from Developer access.");
270
- }
271
- const expectedUserId = env.TORMIE_EXPECTED_USER_ID.toLowerCase();
272
- const client = new TormieClient({ baseUrl: origin, token: env.TORMIE_TOKEN, expectedUserId, fetchImpl });
273
- async function status() {
274
- const session = await client.session();
275
- if (!session?.user) throw new PreviewError("grant_unavailable", "Check the token expiry or revocation in Developer access.");
276
- if (session.user.id !== expectedUserId) throw new PreviewError("workspace_mismatch", "Check the approved workspace UUID in your secret configuration.");
277
- const grant = session.token;
278
- if (grant?.kind !== "api" || grant.scopes?.length !== 1 || grant.scopes[0] !== scope) {
279
- throw new PreviewError("knowledge_grant_required", "Create a dedicated knowledge-read token in Developer access.");
280
- }
281
- const config = await client.config();
282
- if (config?.capabilities?.cli_knowledge_read !== true) {
283
- throw new PreviewError("service_unsupported", "This Tormie service does not offer the CLI Beta grant yet.");
284
- }
285
- return {
286
- authenticated: true,
287
- origin,
288
- account: { id: session.user.id, email: session.user.email },
289
- scopes: [scope],
290
- expires_at: grant.expires_at,
291
- capabilities: { cli_knowledge_read: true }
292
- };
293
- }
294
- async function read(command, input) {
295
- const { result } = await client.request("/card-tools/call", { method: "POST", body: { name: actions[command], arguments: input } });
296
- if (!result || typeof result !== "object" || Array.isArray(result) || Buffer.byteLength(JSON.stringify(result)) > 1e4) {
297
- throw new PreviewError("invalid_result", "Tormie did not return a bounded source result. Run tormie auth status and try again.");
298
- }
299
- return result;
300
- }
301
- return { status, read };
302
- }
303
-
304
- // packages/public-cli/cli.mjs
305
- var version = package_default.version;
306
- var entry = fileURLToPath(import.meta.url);
307
- var mcpEntry = fileURLToPath(new URL("./mcp.mjs", import.meta.url));
308
- var maxInput = 64 * 1024;
309
- var help = `Tormie CLI \u2014 read and cite your notes
310
-
311
- tormie setup [--open] Follow the Web authorization steps
312
- tormie auth status Verify workspace and grant
313
- tormie search --query "smaller experiment" --limit 5
314
- tormie read --input-stdin Read one exact source or a batch
315
- tormie schema search|read Print the machine-readable schema
316
- tormie doctor [--json] Inspect the local installation
317
- tormie mcp config Show local MCP launch settings
318
- tormie --version
319
-
320
- For exact reads, pass a search item's read_args as JSON on stdin.
321
- For help setting up a scoped credential, run tormie setup.
322
- `;
323
- var setup = `1. Sign in to Tormie Web and open Developer access.
324
- ${developerUrl}
325
- 2. Create a separate knowledge-read token for this terminal. Put it in your host
326
- secret store and inject TORMIE_TOKEN into the Tormie process.
327
- 3. Set TORMIE_EXPECTED_USER_ID to the displayed workspace UUID.
328
- 4. Run tormie auth status, then tormie search --query "smaller experiment".
329
-
330
- You can revoke this token in Developer access.
331
- `;
332
- var commandHelp = {
333
- setup: "tormie setup [--open]\nGet the authorization steps, or open Developer access in your browser.",
334
- auth: "tormie auth status\nVerify your configured workspace, grant and expiry.",
335
- search: "tormie search --query TEXT [--limit 1\u201320] [--cursor CURSOR]\nUse the returned read_args to read an exact source. Follow next_cursor for the next result page.",
336
- read: "tormie read --input-stdin\nPass a search result\u2019s read_args or a JSON object containing requests. See tormie schema read.",
337
- doctor: "tormie doctor [--json]\nInspect the local executable and PATH without signing in.",
338
- mcp: "tormie mcp config\nPrint a local launch command and the names of the required environment variables."
339
- };
340
- var json = (value) => `${JSON.stringify(value)}
341
- `;
342
- var is = (args, ...words) => args.length === words.length && words.every((word, i) => args[i] === word);
343
- async function doctor(env) {
344
- const executable = await realpath(entry);
345
- let pathHit = null;
346
- for (const directory of env.PATH?.split(delimiter) ?? []) {
347
- const command = resolve(directory, "tormie");
348
- try {
349
- await access(command, constants.X_OK);
350
- if (!(await stat(command)).isFile()) continue;
351
- pathHit = { command, target: await realpath(command) };
352
- break;
353
- } catch {
354
- }
355
- }
356
- const state = !pathHit ? "missing" : pathHit.target === executable ? "ready" : "shadowed";
357
- const next = {
358
- ready: "Run tormie setup to connect your workspace.",
359
- missing: "Add your npm binary directory to PATH or use npm exec with the exact package version.",
360
- shadowed: "Run type -a tormie and select the intended CLI by absolute path."
361
- };
362
- return { schema_version: 1, version, channel: "npm-beta", executable, node: process.versions.node, platform: process.platform, arch: process.arch, origin, path: { state, hit: pathHit }, next_action: next[state] };
363
- }
364
- async function readStdin(stdin) {
365
- if (stdin.isTTY) throw invalid("Pipe a JSON object into tormie read --input-stdin.");
366
- const chunks = [];
367
- let size = 0;
368
- for await (const data of stdin) {
369
- const chunk = Buffer.from(data);
370
- size += chunk.length;
371
- if (size > maxInput) throw invalid("Use a JSON input of at most 64 KiB.");
372
- chunks.push(chunk);
373
- }
374
- try {
375
- return JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(Buffer.concat(chunks)));
376
- } catch {
377
- throw invalid("Provide one UTF-8 JSON object on stdin.");
378
- }
379
- }
380
- function searchInput(args) {
381
- const input = {};
382
- const fields2 = { "--query": "query", "--limit": "limit", "--cursor": "cursor" };
383
- for (let index = 0; index < args.length; index += 2) {
384
- const flag = args[index], value = args[index + 1];
385
- const field = Object.hasOwn(fields2, flag) && fields2[flag];
386
- if (!field || Object.hasOwn(input, field) || !value || value.startsWith("--")) {
387
- throw invalid("Use tormie search --query TEXT [--limit 1\u201320] [--cursor CURSOR].");
388
- }
389
- if (field === "limit" && !/^\d{1,2}$/.test(value)) throw invalid("Use a search limit from 1 to 20.");
390
- input[field] = field === "limit" ? Number(value) : value;
391
- }
392
- if (!input.query?.trim()) throw invalid("Provide a search query using --query TEXT.");
393
- return input;
394
- }
395
- async function openDeveloperPage() {
396
- const commands = { darwin: "/usr/bin/open", linux: "xdg-open" };
397
- const command = commands[process.platform];
398
- if (!command) throw invalid(`Open ${developerUrl} in your browser.`);
399
- try {
400
- await promisify(execFile)(command, [developerUrl], { timeout: 5e3, maxBuffer: 8192 });
401
- } catch {
402
- throw invalid(`Open ${developerUrl} in your browser.`);
403
- }
404
- }
405
- async function runCli(args, { env = process.env, stdin = process.stdin, fetchImpl = fetch } = {}) {
406
- if (!args.length || is(args, "--help") || is(args, "help")) return help;
407
- if (args.length === 2 && (args[0] === "help" || args[1] === "--help")) {
408
- const command2 = args[0] === "help" ? args[1] : args[0];
409
- if (!Object.hasOwn(commandHelp, command2)) throw invalid("Run tormie --help for available commands.");
410
- return `${commandHelp[command2]}
411
- `;
412
- }
413
- if (is(args, "--version")) return `tormie ${version} (npm beta)
414
- `;
415
- if (is(args, "setup") || is(args, "setup", "--open")) {
416
- if (args.length === 2) await openDeveloperPage();
417
- return setup;
418
- }
419
- if (is(args, "doctor") || is(args, "doctor", "--json")) {
420
- const info = await doctor(env);
421
- return args.length === 2 ? json(info) : `Tormie ${info.version} \xB7 ${info.channel}
422
- ${info.executable}
423
- PATH: ${info.path.state}
424
- ${info.next_action}
425
- `;
426
- }
427
- if (is(args, "mcp", "config")) {
428
- return json({ command: process.execPath, args: [mcpEntry], required_environment: ["TORMIE_TOKEN", "TORMIE_EXPECTED_USER_ID"] });
429
- }
430
- if (is(args, "schema", "search") || is(args, "schema", "read")) return json(describe(args[1]));
431
- if (is(args, "auth", "status") || is(args, "agent", "status")) {
432
- return json(await createKnowledgeClient(env, fetchImpl).status());
433
- }
434
- const [command, ...flags] = args;
435
- if (command !== "search" && !is(args, "read", "--input-stdin")) throw invalid("Run tormie --help for available commands.");
436
- const input = command === "search" ? searchInput(flags) : await readStdin(stdin);
437
- const validated = inputSchema(command).safeParse(input);
438
- if (!validated.success) throw invalid(`Check the expected input with tormie schema ${command}.`);
439
- const client = createKnowledgeClient(env, fetchImpl);
440
- await client.status();
441
- return json(await client.read(command, validated.data));
442
- }
443
- if (process.argv[1] && pathToFileURL(await realpath(process.argv[1])).href === import.meta.url) {
444
- try {
445
- process.stdout.write(await runCli(process.argv.slice(2)));
446
- } catch (error) {
447
- process.stderr.write(json(errorOutput(error)));
448
- process.exitCode = error.exitCode ?? 1;
449
- }
450
- }
451
- export {
452
- runCli
453
- };