@fadhilp/stateql 0.14.0 → 0.15.0

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.
@@ -0,0 +1,3 @@
1
+ import type { Response } from "./types.js";
2
+ /** Compacts a response for model context, as the CLI `agent` output mode does. */
3
+ export declare function agentResponse(result: Response<unknown>, commandName: string): Record<string, unknown>;
@@ -0,0 +1,213 @@
1
+ import { isColumns, isRecord } from "./util.js";
2
+ const RESULT_COMMANDS = new Set(["query", "mongo.query", "redis.query", "filter", "show"]);
3
+ const FALSE_DEFAULT_KEYS = ["cached", "duplicate", "duplicate_override"];
4
+ const SHARED_HISTORY_KEYS = ["session_id", "actor_id", "actor_name", "origin"];
5
+ // The caller already holds the handle it passed to these commands.
6
+ const HANDLE_ECHO_COMMANDS = new Set(["rows", "count", "columns"]);
7
+ const WRITE_COMMANDS = new Set(["exec", "mongo.exec", "redis.exec", "apply"]);
8
+ const COMMAND_ALIASES = {
9
+ "objects.list": "objects",
10
+ "object.describe": "object",
11
+ };
12
+ /** Compacts a response for model context, as the CLI `agent` output mode does. */
13
+ export function agentResponse(result, commandName) {
14
+ const currentCommand = COMMAND_ALIASES[commandName] ?? commandName;
15
+ if (!result.ok)
16
+ return { ok: false, error: result.error };
17
+ if (!isRecord(result.data))
18
+ return { ok: true, data: result.data };
19
+ const data = { ...result.data };
20
+ const handleKey = primaryHandleKey(currentCommand);
21
+ let handle = handleKey && typeof data[handleKey] === "string" && data[handleKey]
22
+ ? data[handleKey]
23
+ : undefined;
24
+ if (handle && handleKey)
25
+ delete data[handleKey];
26
+ const generatedAlias = data.display_alias;
27
+ delete data.display_alias;
28
+ // Generated aliases cannot be reassigned, so they are stable short result handles.
29
+ if (RESULT_COMMANDS.has(currentCommand) && typeof generatedAlias === "string") {
30
+ handle = generatedAlias;
31
+ if (data.alias === generatedAlias)
32
+ delete data.alias;
33
+ }
34
+ const isResult = RESULT_COMMANDS.has(currentCommand) &&
35
+ typeof data.rows === "number" &&
36
+ Array.isArray(data.preview);
37
+ if (isResult) {
38
+ data.total = data.rows;
39
+ data.next_offset = data.truncated ? data.preview.length : null;
40
+ data.rows = data.preview;
41
+ delete data.preview;
42
+ delete data.preview_count;
43
+ delete data.truncated;
44
+ delete data.storage;
45
+ delete data.state_version;
46
+ delete data.duplicate_of;
47
+ }
48
+ else if (currentCommand === "rows") {
49
+ delete data.offset;
50
+ delete data.limit;
51
+ delete data.returned;
52
+ delete data.truncated;
53
+ }
54
+ else if (currentCommand === "count" && typeof data.rows === "number") {
55
+ data.total = data.rows;
56
+ delete data.rows;
57
+ }
58
+ else if (WRITE_COMMANDS.has(currentCommand)) {
59
+ delete data.actor_id;
60
+ delete data.plan_id;
61
+ delete data.state_version_before;
62
+ if (typeof data.status === "string")
63
+ delete data.committed;
64
+ }
65
+ else if (currentCommand === "history" &&
66
+ Array.isArray(data.history) &&
67
+ data.history.every(isRecord)) {
68
+ Object.assign(data, compactHistory(data.history));
69
+ }
70
+ else if (currentCommand === "inspect" && Array.isArray(data.columns)) {
71
+ data.columns = data.columns.map(withoutFalsePrimaryKey);
72
+ }
73
+ else if (currentCommand === "capabilities" && isRecord(data.features)) {
74
+ const features = data.features;
75
+ data.features = Object.keys(features).filter((key) => features[key] === true);
76
+ }
77
+ else if (currentCommand === "objects" &&
78
+ Array.isArray(data.objects) &&
79
+ data.objects.every(isRecord)) {
80
+ const objects = data.objects.every(hasDerivedIdentity)
81
+ ? data.objects.map(withoutIdentity)
82
+ : data.objects;
83
+ const table = columnarRows(objects, undefined);
84
+ delete data.objects;
85
+ Object.assign(data, { columns: table.columns, objects: table.rows });
86
+ }
87
+ else if (currentCommand === "object" &&
88
+ isRecord(data.object) &&
89
+ hasDerivedIdentity(data.object)) {
90
+ data.object = withoutIdentity(data.object);
91
+ }
92
+ if (isResult || (currentCommand === "rows" && Array.isArray(data.rows))) {
93
+ const table = columnarRows(data.rows, data.columns);
94
+ delete data.columns;
95
+ delete data.rows;
96
+ Object.assign(data, table);
97
+ }
98
+ const hasMoreRows = data.next_offset !== null && data.next_offset !== undefined;
99
+ const warnings = result.warnings.filter((warning) => warning.code !== "NON_DETERMINISTIC_PAGINATION" || hasMoreRows);
100
+ dropFalseDefaults(data);
101
+ for (const key of ["ok", "error", "handle", "warnings"]) {
102
+ if (!(key in data))
103
+ continue;
104
+ data[`data_${key}`] = data[key];
105
+ delete data[key];
106
+ }
107
+ return {
108
+ ok: true,
109
+ ...(handle && !HANDLE_ECHO_COMMANDS.has(currentCommand) ? { handle } : {}),
110
+ ...withoutNulls(data),
111
+ ...(warnings.length ? { warnings } : {}),
112
+ };
113
+ }
114
+ // Rows with differing keys (e.g. MongoDB documents) stay objects so missing and null remain distinct.
115
+ function columnarRows(rows, columns) {
116
+ const names = isColumns(columns)
117
+ ? columns.map((column) => column.name)
118
+ : Object.keys(rows[0] ?? {});
119
+ if (names.length === 0)
120
+ return { rows };
121
+ const nameSet = new Set(names);
122
+ const hasColumnKeys = (row) => {
123
+ if (!isRecord(row))
124
+ return false;
125
+ const keys = Object.keys(row);
126
+ return keys.length === names.length && keys.every((key) => nameSet.has(key));
127
+ };
128
+ if (!rows.every(hasColumnKeys))
129
+ return { rows };
130
+ return {
131
+ columns: names,
132
+ rows: rows.map((row) => names.map((name) => row[name])),
133
+ };
134
+ }
135
+ function compactHistory(entries) {
136
+ const shared = {};
137
+ for (const key of SHARED_HISTORY_KEYS) {
138
+ const value = entries[0]?.[key];
139
+ if (value === undefined)
140
+ continue;
141
+ if (entries.every((entry) => entry[key] === value))
142
+ shared[key] = value;
143
+ }
144
+ const history = entries.map((entry) => {
145
+ const compact = withoutNulls(entry);
146
+ dropFalseDefaults(compact);
147
+ for (const key of Object.keys(shared))
148
+ delete compact[key];
149
+ return compact;
150
+ });
151
+ return { ...shared, history };
152
+ }
153
+ function hasDerivedIdentity(object) {
154
+ const qualifiedName = typeof object.schema === "string"
155
+ ? `${object.schema}.${String(object.name)}`
156
+ : object.name;
157
+ return object.identity === undefined || object.identity === qualifiedName;
158
+ }
159
+ function withoutIdentity(object) {
160
+ const compact = { ...object };
161
+ delete compact.identity;
162
+ return compact;
163
+ }
164
+ function withoutFalsePrimaryKey(column) {
165
+ if (!isRecord(column) || column.primary_key !== false)
166
+ return column;
167
+ const compact = { ...column };
168
+ delete compact.primary_key;
169
+ return compact;
170
+ }
171
+ function dropFalseDefaults(record) {
172
+ for (const key of FALSE_DEFAULT_KEYS) {
173
+ if (record[key] === false)
174
+ delete record[key];
175
+ }
176
+ }
177
+ function withoutNulls(record) {
178
+ return Object.fromEntries(Object.entries(record).filter(([, value]) => value !== null));
179
+ }
180
+ function primaryHandleKey(currentCommand) {
181
+ const keys = {
182
+ query: "result_id",
183
+ "mongo.query": "result_id",
184
+ "redis.query": "result_id",
185
+ filter: "result_id",
186
+ show: "result_id",
187
+ rows: "result_id",
188
+ count: "result_id",
189
+ columns: "result_id",
190
+ export: "result_id",
191
+ alias: "result_id",
192
+ "alias.set": "result_id",
193
+ exec: "operation_id",
194
+ "mongo.exec": "operation_id",
195
+ "redis.exec": "operation_id",
196
+ receipt: "operation_id",
197
+ apply: "operation_id",
198
+ plan: "plan_id",
199
+ "mongo.plan": "plan_id",
200
+ "redis.plan": "plan_id",
201
+ connect: "connection_id",
202
+ transaction: "transaction_id",
203
+ "transaction.begin": "transaction_id",
204
+ "transaction.status": "transaction_id",
205
+ "transaction.commit": "transaction_id",
206
+ "transaction.rollback": "transaction_id",
207
+ session: "session_id",
208
+ "session.start": "session_id",
209
+ "session.show": "session_id",
210
+ "session.close": "session_id",
211
+ };
212
+ return keys[currentCommand];
213
+ }
package/dist/src/cli.js CHANGED
@@ -6,13 +6,7 @@ import { parseArgs } from "node:util";
6
6
  import { BSON } from "mongodb";
7
7
  import { exitCodeFor } from "./errors.js";
8
8
  import { StateQL } from "./stateql.js";
9
- import { isColumns, isRecord } from "./util.js";
10
- const RESULT_COMMANDS = new Set(["query", "mongo.query", "filter", "show"]);
11
- const FALSE_DEFAULT_KEYS = ["cached", "duplicate", "duplicate_override"];
12
- const SHARED_HISTORY_KEYS = ["session_id", "actor_id", "actor_name", "origin"];
13
- // The caller already holds the handle it passed to these commands.
14
- const HANDLE_ECHO_COMMANDS = new Set(["rows", "count", "columns"]);
15
- const WRITE_COMMANDS = new Set(["exec", "mongo.exec", "apply"]);
9
+ import { agentResponse } from "./agent-response.js";
16
10
  const parsed = parseArgs({
17
11
  allowPositionals: true,
18
12
  strict: true,
@@ -105,8 +99,8 @@ async function runSingle() {
105
99
  catch (error) {
106
100
  response = cliFailure(error);
107
101
  }
108
- const responseCommand = command === "mongo" && subcommand
109
- ? `mongo.${subcommand}`
102
+ const responseCommand = (command === "mongo" || command === "redis") && subcommand
103
+ ? `${command}.${subcommand}`
110
104
  : command ?? "";
111
105
  print(response, mode, responseCommand);
112
106
  if (!response.ok)
@@ -537,208 +531,11 @@ function print(result, mode, currentCommand) {
537
531
  return;
538
532
  }
539
533
  if (mode === "agent") {
540
- console.log(JSON.stringify(toAgentResponse(result, currentCommand)));
534
+ console.log(JSON.stringify(agentResponse(result, currentCommand)));
541
535
  return;
542
536
  }
543
537
  console.log(mode === "json" ? JSON.stringify(result, null, 2) : JSON.stringify(result));
544
538
  }
545
- function toAgentResponse(result, currentCommand) {
546
- if (!result.ok)
547
- return { ok: false, error: result.error };
548
- if (!isRecord(result.data))
549
- return { ok: true, data: result.data };
550
- const data = { ...result.data };
551
- const handleKey = primaryHandleKey(currentCommand);
552
- let handle = handleKey && typeof data[handleKey] === "string" && data[handleKey]
553
- ? data[handleKey]
554
- : undefined;
555
- if (handle && handleKey)
556
- delete data[handleKey];
557
- const generatedAlias = data.display_alias;
558
- delete data.display_alias;
559
- // Generated aliases cannot be reassigned, so they are stable short result handles.
560
- if (RESULT_COMMANDS.has(currentCommand) && typeof generatedAlias === "string") {
561
- handle = generatedAlias;
562
- if (data.alias === generatedAlias)
563
- delete data.alias;
564
- }
565
- const isResult = RESULT_COMMANDS.has(currentCommand) &&
566
- typeof data.rows === "number" &&
567
- Array.isArray(data.preview);
568
- if (isResult) {
569
- data.total = data.rows;
570
- data.next_offset = data.truncated ? data.preview.length : null;
571
- data.rows = data.preview;
572
- delete data.preview;
573
- delete data.preview_count;
574
- delete data.truncated;
575
- delete data.storage;
576
- delete data.state_version;
577
- delete data.duplicate_of;
578
- }
579
- else if (currentCommand === "rows") {
580
- delete data.offset;
581
- delete data.limit;
582
- delete data.returned;
583
- delete data.truncated;
584
- }
585
- else if (currentCommand === "count" && typeof data.rows === "number") {
586
- data.total = data.rows;
587
- delete data.rows;
588
- }
589
- else if (WRITE_COMMANDS.has(currentCommand)) {
590
- delete data.actor_id;
591
- delete data.plan_id;
592
- delete data.state_version_before;
593
- if (typeof data.status === "string")
594
- delete data.committed;
595
- }
596
- else if (currentCommand === "history" &&
597
- Array.isArray(data.history) &&
598
- data.history.every(isRecord)) {
599
- Object.assign(data, compactHistory(data.history));
600
- }
601
- else if (currentCommand === "inspect" && Array.isArray(data.columns)) {
602
- data.columns = data.columns.map(withoutFalsePrimaryKey);
603
- }
604
- else if (currentCommand === "capabilities" && isRecord(data.features)) {
605
- const features = data.features;
606
- data.features = Object.keys(features).filter((key) => features[key] === true);
607
- }
608
- else if (currentCommand === "objects" &&
609
- Array.isArray(data.objects) &&
610
- data.objects.every(isRecord)) {
611
- const objects = data.objects.every(hasDerivedIdentity)
612
- ? data.objects.map(withoutIdentity)
613
- : data.objects;
614
- const table = columnarRows(objects, undefined);
615
- delete data.objects;
616
- Object.assign(data, { columns: table.columns, objects: table.rows });
617
- }
618
- else if (currentCommand === "object" &&
619
- isRecord(data.object) &&
620
- hasDerivedIdentity(data.object)) {
621
- data.object = withoutIdentity(data.object);
622
- }
623
- if (isResult || (currentCommand === "rows" && Array.isArray(data.rows))) {
624
- const table = columnarRows(data.rows, data.columns);
625
- delete data.columns;
626
- delete data.rows;
627
- Object.assign(data, table);
628
- }
629
- const hasMoreRows = data.next_offset !== null && data.next_offset !== undefined;
630
- const warnings = result.warnings.filter((warning) => warning.code !== "NON_DETERMINISTIC_PAGINATION" || hasMoreRows);
631
- dropFalseDefaults(data);
632
- for (const key of ["ok", "error", "handle", "warnings"]) {
633
- if (!(key in data))
634
- continue;
635
- data[`data_${key}`] = data[key];
636
- delete data[key];
637
- }
638
- return {
639
- ok: true,
640
- ...(handle && !HANDLE_ECHO_COMMANDS.has(currentCommand) ? { handle } : {}),
641
- ...withoutNulls(data),
642
- ...(warnings.length ? { warnings } : {}),
643
- };
644
- }
645
- // Rows with differing keys (e.g. MongoDB documents) stay objects so missing and null remain distinct.
646
- function columnarRows(rows, columns) {
647
- const names = isColumns(columns)
648
- ? columns.map((column) => column.name)
649
- : Object.keys(rows[0] ?? {});
650
- if (names.length === 0)
651
- return { rows };
652
- const nameSet = new Set(names);
653
- const hasColumnKeys = (row) => {
654
- if (!isRecord(row))
655
- return false;
656
- const keys = Object.keys(row);
657
- return keys.length === names.length && keys.every((key) => nameSet.has(key));
658
- };
659
- if (!rows.every(hasColumnKeys))
660
- return { rows };
661
- return {
662
- columns: names,
663
- rows: rows.map((row) => names.map((name) => row[name])),
664
- };
665
- }
666
- function compactHistory(entries) {
667
- const shared = {};
668
- for (const key of SHARED_HISTORY_KEYS) {
669
- const value = entries[0]?.[key];
670
- if (value === undefined)
671
- continue;
672
- if (entries.every((entry) => entry[key] === value))
673
- shared[key] = value;
674
- }
675
- const history = entries.map((entry) => {
676
- const compact = withoutNulls(entry);
677
- dropFalseDefaults(compact);
678
- for (const key of Object.keys(shared))
679
- delete compact[key];
680
- return compact;
681
- });
682
- return { ...shared, history };
683
- }
684
- function hasDerivedIdentity(object) {
685
- const qualifiedName = typeof object.schema === "string"
686
- ? `${object.schema}.${String(object.name)}`
687
- : object.name;
688
- return object.identity === undefined || object.identity === qualifiedName;
689
- }
690
- function withoutIdentity(object) {
691
- const compact = { ...object };
692
- delete compact.identity;
693
- return compact;
694
- }
695
- function withoutFalsePrimaryKey(column) {
696
- if (!isRecord(column) || column.primary_key !== false)
697
- return column;
698
- const compact = { ...column };
699
- delete compact.primary_key;
700
- return compact;
701
- }
702
- function dropFalseDefaults(record) {
703
- for (const key of FALSE_DEFAULT_KEYS) {
704
- if (record[key] === false)
705
- delete record[key];
706
- }
707
- }
708
- function withoutNulls(record) {
709
- return Object.fromEntries(Object.entries(record).filter(([, value]) => value !== null));
710
- }
711
- function primaryHandleKey(currentCommand) {
712
- const keys = {
713
- query: "result_id",
714
- "mongo.query": "result_id",
715
- filter: "result_id",
716
- show: "result_id",
717
- rows: "result_id",
718
- count: "result_id",
719
- columns: "result_id",
720
- export: "result_id",
721
- alias: "result_id",
722
- "alias.set": "result_id",
723
- exec: "operation_id",
724
- "mongo.exec": "operation_id",
725
- receipt: "operation_id",
726
- apply: "operation_id",
727
- plan: "plan_id",
728
- "mongo.plan": "plan_id",
729
- connect: "connection_id",
730
- transaction: "transaction_id",
731
- "transaction.begin": "transaction_id",
732
- "transaction.status": "transaction_id",
733
- "transaction.commit": "transaction_id",
734
- "transaction.rollback": "transaction_id",
735
- session: "session_id",
736
- "session.start": "session_id",
737
- "session.show": "session_id",
738
- "session.close": "session_id",
739
- };
740
- return keys[currentCommand];
741
- }
742
539
  function cliFailure(error) {
743
540
  return {
744
541
  ok: false,
@@ -1,4 +1,5 @@
1
1
  export { StateQL } from "./stateql.js";
2
+ export { agentResponse } from "./agent-response.js";
2
3
  export { CredentialResolutionError, StateQLError, exitCodeFor, } from "./errors.js";
3
4
  export type { CredentialResolutionFailure } from "./errors.js";
4
5
  export type { TableChange, TableIdentity, TableUpdate } from "./table-editor.js";
package/dist/src/index.js CHANGED
@@ -1,2 +1,3 @@
1
1
  export { StateQL } from "./stateql.js";
2
+ export { agentResponse } from "./agent-response.js";
2
3
  export { CredentialResolutionError, StateQLError, exitCodeFor, } from "./errors.js";
package/docs/library.md CHANGED
@@ -4,6 +4,7 @@
4
4
 
5
5
  - [Getting started](#getting-started)
6
6
  - [Responses and command context](#responses-and-command-context)
7
+ - [Compact responses for model context](#compact-responses-for-model-context)
7
8
  - [Actor workspaces](#actor-workspaces)
8
9
  - [Credential resolution](#credential-resolution)
9
10
  - [Safe profile updates](#safe-profile-updates)
@@ -94,6 +95,23 @@ direct calls and `executeCommand(command)` calls are recorded as `legacy`.
94
95
  `BatchCommand` cannot attribute the command. `batch` accepts the same trusted
95
96
  context as `options.executionContext` for all commands in that batch.
96
97
 
98
+ ### Compact responses for model context
99
+
100
+ When a response goes into a model's context, pass it through `agentResponse`
101
+ with the batch command name. It returns the same compact shape as the CLI
102
+ `agent` output mode (see [output modes](cli.md#output-modes)). Keep the full
103
+ response for application logic.
104
+
105
+ ```ts
106
+ import { agentResponse } from "@fadhilp/stateql";
107
+
108
+ const response = await stateql.executeCommand(command, { origin: "model" });
109
+ const forModel = JSON.stringify(agentResponse(response, command.command));
110
+ ```
111
+
112
+ `objects.list` and `object.describe` are accepted as names for catalog
113
+ responses from `listObjects` and `describeObject`.
114
+
97
115
  ## Actor workspaces
98
116
 
99
117
  `StateQL.forWorkspace(...)` is a trusted-host primitive that atomically creates
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fadhilp/stateql",
3
- "version": "0.14.0",
3
+ "version": "0.15.0",
4
4
  "description": "Stateful, agent-oriented database CLI for safe result reuse",
5
5
  "repository": {
6
6
  "type": "git",