@fadhilp/stateql 0.13.2 → 0.14.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.
package/dist/src/sql.js CHANGED
@@ -1,7 +1,14 @@
1
1
  import { createRequire } from "node:module";
2
2
  import { StateQLError } from "./errors.js";
3
- const { Parser } = createRequire(import.meta.url)("node-sql-parser");
4
- const parser = new Parser();
3
+ const require = createRequire(import.meta.url);
4
+ let parser;
5
+ function sqlParser() {
6
+ if (!parser) {
7
+ const { Parser } = require("node-sql-parser");
8
+ parser = new Parser();
9
+ }
10
+ return parser;
11
+ }
5
12
  const SUPPORTED_STATEMENTS = new Set([
6
13
  "select",
7
14
  "insert",
@@ -44,13 +51,20 @@ export function analyzeSql(sql, driver) {
44
51
  }
45
52
  }
46
53
  function parseSqlStatement(sql, driver) {
54
+ const parser = sqlParser();
47
55
  const database = driver === "postgres"
48
56
  ? "Postgresql"
49
57
  : driver === "mysql"
50
58
  ? "MySQL"
51
59
  : "Sqlite";
52
60
  const parserSql = driver === "postgres" ? postgresParserSql(sql) : sql;
53
- const parsed = parser.astify(parserSql, { database });
61
+ let parsed;
62
+ try {
63
+ parsed = parser.astify(parserSql, { database });
64
+ }
65
+ catch (error) {
66
+ throw new StateQLError("INVALID_SQL", syntaxErrorMessage(error, parserSql));
67
+ }
54
68
  if (Array.isArray(parsed) && parsed.length !== 1) {
55
69
  throw new StateQLError("INVALID_SQL", "Exactly one SQL statement is required.");
56
70
  }
@@ -1065,6 +1079,17 @@ function postgresBlockCommentEnd(sql, start) {
1065
1079
  }
1066
1080
  return undefined;
1067
1081
  }
1082
+ // The parser lists every expected token (often 500+ characters); position and nearby text are enough to fix the SQL.
1083
+ function syntaxErrorMessage(error, sql) {
1084
+ const start = error.location?.start;
1085
+ if (!start)
1086
+ return error instanceof Error ? error.message : "Invalid SQL.";
1087
+ const near = sql.slice(start.offset, start.offset + 20).split("\n")[0];
1088
+ const position = `line ${start.line}, column ${start.column}`;
1089
+ return near
1090
+ ? `Syntax error at ${position} near "${near}".`
1091
+ : `Syntax error at ${position}: unexpected end of input.`;
1092
+ }
1068
1093
  function postgresParserSql(sql) {
1069
1094
  const output = sql.split("");
1070
1095
  const orderDepths = new Set();
@@ -1,5 +1,5 @@
1
1
  import { type TableChange } from "./table-editor.js";
2
- import type { ActorLinkData, ActorResolutionData, ActorsData, ActorUnlinkData, AliasData, ApplyData, BatchCommand, CommandExecutionContext, CommandOrigin, BatchOptions, CapabilitiesData, CatalogObject, DescribeObjectData, ListObjectsData, ListObjectsFilter, CloseSessionData, ColumnsData, CommitTransactionData, ConnectOptions, ConnectionData, CountData, DisconnectData, DoctorData, ExecData, ExecOptions, ExecutionOptions, ExportData, FilterOptions, HistoryData, HistoryOptions, OperationData, PlanData, PlanOptions, ProfileData, ProfilesData, ProfileOptions, ProfileUpdateOptions, MongoExecOptions, MongoPlanOptions, MongoQueryOptions, MongoReadCommand, MongoWriteCommand, RedisCommand, RedisExecOptions, RedisPlanOptions, RedisQueryOptions, PurgeData, QueryOptions, RemovedProfileData, Response, ResultData, RollbackTransactionData, RowsData, RowsOptions, Column, StateQLActorOptions, StateQLOptions, StateQLWorkspaceOptions, StateQLSnapshot, StateQLSnapshotOptions, StatusData, SessionData, SessionsData, SessionSummaryData, TransactionData } from "./types.js";
2
+ import type { ActorData, ActorLinkData, ActorResolutionData, ActorsData, ActorUnlinkData, AliasData, ApplyData, BatchCommand, CommandExecutionContext, CommandOrigin, BatchOptions, CapabilitiesData, CatalogObject, DescribeObjectData, ListObjectsData, ListObjectsFilter, CloseSessionData, ColumnsData, CommitTransactionData, ConnectOptions, ConnectionData, CountData, DisconnectData, DoctorData, ExecData, ExecOptions, ExecutionOptions, ExportData, FilterOptions, HistoryData, HistoryOptions, OperationData, PlanData, PlanOptions, ProfileData, ProfilesData, ProfileOptions, ProfileUpdateOptions, MongoExecOptions, MongoPlanOptions, MongoQueryOptions, MongoReadCommand, MongoWriteCommand, RedisCommand, RedisExecOptions, RedisPlanOptions, RedisQueryOptions, PurgeData, QueryOptions, RemovedProfileData, Response, ResultData, RollbackTransactionData, RowsData, RowsOptions, Column, StateQLActorOptions, StateQLOptions, StateQLWorkspaceOptions, StateQLSnapshot, StateQLSnapshotOptions, StatusData, SessionData, SessionsData, SessionSummaryData, TransactionData } from "./types.js";
3
3
  export declare class StateQL {
4
4
  /** Runtime contract marker for passwordRef/password_ref support. */
5
5
  static readonly passwordReferenceVersion: 1;
@@ -39,6 +39,8 @@ export declare class StateQL {
39
39
  status(): Promise<Response<StatusData>>;
40
40
  linkActor(session: string, actorId: string): Promise<Response<ActorLinkData>>;
41
41
  unlinkActor(session: string, actorId: string): Promise<Response<ActorUnlinkData>>;
42
+ showActor(): Promise<Response<ActorData>>;
43
+ setActorName(name: string): Promise<Response<ActorData>>;
42
44
  listActors(session: string): Promise<Response<ActorsData>>;
43
45
  resolveActor(actorId: string): Promise<Response<ActorResolutionData>>;
44
46
  startSession(name: string): Promise<Response<SessionData>>;
@@ -132,6 +134,7 @@ export declare class StateQL {
132
134
  private requireActiveTransaction;
133
135
  private requireSelectedSession;
134
136
  private validateActorId;
137
+ private validateActorName;
135
138
  private throwMembershipDenied;
136
139
  private resolveConnectionSource;
137
140
  private resolveCredential;
@@ -6,7 +6,7 @@ import { basename, resolve } from "node:path";
6
6
  import { env } from "node:process";
7
7
  import { AdapterExecutionError, AdapterWriteError, BatchWriteError, createAdapter, createAdapterContext, } from "./adapters.js";
8
8
  import { confidence, credentialSource, databaseIdentity, databaseUrlHasSecret, detectDriver, isEnvironmentName, injectPassword, mongoDatabaseName, redisDatabaseName, normalizeSqliteSource, validateCredentialRef, validatePasswordReferenceTarget, validateProfileName, version, } from "./connection.js";
9
- import { asStateQLError, CredentialResolutionError, StateQLError, } from "./errors.js";
9
+ import { asStateQLError, CredentialResolutionError, isTransientDatabaseError, StateQLError, } from "./errors.js";
10
10
  import { analyzeMongoWriteSafety, deserializeMongoWriteCommand, serializeMongoCommand, validateMongoReadCommand, validateMongoWriteCommand, MongoAdapter, } from "./mongodb.js";
11
11
  import { deserializeRedisCommand, RedisAdapter, serializeRedisCommand, validateRedisReadCommand, validateRedisWriteCommand, } from "./redis.js";
12
12
  import { filterMaterializedRows, prepareFilterStatement, validateFilterParameters, } from "./filter.js";
@@ -411,6 +411,7 @@ export class StateQL {
411
411
  if (!this.store.isSessionMember(session.id, this.actorId)) {
412
412
  throw new StateQLError("PERMISSION_DENIED", `Actor "${this.actorId}" is not attached to session "${session.name}".`);
413
413
  }
414
+ const actor = this.store.getActor(session.id, this.actorId);
414
415
  const connection = this.store.activeConnection(session);
415
416
  const transaction = session.active_transaction_id
416
417
  ? this.store.getTransaction(session.active_transaction_id)
@@ -433,6 +434,7 @@ export class StateQL {
433
434
  status: session.status,
434
435
  },
435
436
  actor_id: this.actorId,
437
+ actor_name: actor.actor_name,
436
438
  connection: connection
437
439
  ? {
438
440
  connection_id: connection.id,
@@ -479,11 +481,13 @@ export class StateQL {
479
481
  const transaction = session.active_transaction_id
480
482
  ? this.store.getTransaction(session.active_transaction_id)
481
483
  : undefined;
484
+ const actor = this.store.getActor(session.id, this.actorId);
482
485
  return {
483
486
  data: {
484
487
  session_id: session.id,
485
488
  session_name: session.name,
486
489
  actor_id: this.actorId,
490
+ actor_name: actor.actor_name,
487
491
  connection: connection
488
492
  ? {
489
493
  connection_id: connection.id,
@@ -547,6 +551,42 @@ export class StateQL {
547
551
  };
548
552
  });
549
553
  }
554
+ async showActor() {
555
+ return this.run("actor.show", async (current) => {
556
+ const actor = this.store.getActor(current.id, this.actorId);
557
+ return {
558
+ data: {
559
+ actor_id: actor.actor_id,
560
+ actor_name: actor.actor_name,
561
+ attached_at: actor.attached_at,
562
+ },
563
+ };
564
+ });
565
+ }
566
+ async setActorName(name) {
567
+ return this.run("actor.set-name", async (current) => {
568
+ const actorName = this.validateActorName(name);
569
+ const existing = this.store.getActor(current.id, this.actorId);
570
+ if (existing.actor_name === actorName) {
571
+ return {
572
+ data: {
573
+ actor_id: existing.actor_id,
574
+ actor_name: existing.actor_name,
575
+ attached_at: existing.attached_at,
576
+ },
577
+ };
578
+ }
579
+ const actor = this.store.setActorName(current.id, this.actorId, actorName);
580
+ return {
581
+ data: {
582
+ actor_id: actor.actor_id,
583
+ actor_name: actor.actor_name,
584
+ attached_at: actor.attached_at,
585
+ },
586
+ executed: true,
587
+ };
588
+ }, undefined, actorNameHistoryTarget(name));
589
+ }
550
590
  async listActors(session) {
551
591
  return this.run("actor.list", async (current) => {
552
592
  this.requireSelectedSession(current, session);
@@ -555,6 +595,7 @@ export class StateQL {
555
595
  session_id: current.id,
556
596
  actors: this.store.listActors(current.id).map((member) => ({
557
597
  actor_id: member.actor_id,
598
+ actor_name: member.actor_name,
558
599
  attached_at: member.attached_at,
559
600
  })),
560
601
  },
@@ -770,7 +811,7 @@ export class StateQL {
770
811
  throw stoppedStateQLError(error, true);
771
812
  }
772
813
  throw new StateQLError("QUERY_FAILED", safeCredentialErrorMessage(error, adapterSource), {
773
- retryable: true,
814
+ retryable: isTransientDatabaseError(error),
774
815
  executed: true,
775
816
  });
776
817
  }
@@ -861,7 +902,7 @@ export class StateQL {
861
902
  if (error instanceof AdapterExecutionError) {
862
903
  throw stoppedStateQLError(error, true);
863
904
  }
864
- throw new StateQLError("QUERY_FAILED", safeCredentialErrorMessage(error, adapterSource), { retryable: true, executed: true });
905
+ throw new StateQLError("QUERY_FAILED", safeCredentialErrorMessage(error, adapterSource), { retryable: isTransientDatabaseError(error), executed: true });
865
906
  }
866
907
  finally {
867
908
  await closeAdapterQuietly(adapter);
@@ -906,7 +947,7 @@ export class StateQL {
906
947
  throw error;
907
948
  if (error instanceof AdapterExecutionError)
908
949
  throw stoppedStateQLError(error, true);
909
- throw new StateQLError("QUERY_FAILED", safeCredentialErrorMessage(error, source), { retryable: true, executed: true });
950
+ throw new StateQLError("QUERY_FAILED", safeCredentialErrorMessage(error, source), { retryable: isTransientDatabaseError(error), executed: true });
910
951
  }
911
952
  finally {
912
953
  await closeAdapterQuietly(adapter);
@@ -1653,7 +1694,7 @@ export class StateQL {
1653
1694
  if (error instanceof AdapterExecutionError) {
1654
1695
  throw stoppedStateQLError(error, true);
1655
1696
  }
1656
- throw new StateQLError("QUERY_FAILED", safeCredentialErrorMessage(error, adapterSource), { retryable: true, executed: true });
1697
+ throw new StateQLError("QUERY_FAILED", safeCredentialErrorMessage(error, adapterSource), { retryable: isTransientDatabaseError(error), executed: true });
1657
1698
  }
1658
1699
  finally {
1659
1700
  await closeAdapterQuietly(adapter);
@@ -1718,7 +1759,7 @@ export class StateQL {
1718
1759
  if (error instanceof AdapterExecutionError) {
1719
1760
  throw stoppedStateQLError(error, true);
1720
1761
  }
1721
- throw new StateQLError("QUERY_FAILED", safeCredentialErrorMessage(error, adapterSource), { retryable: true, executed: true });
1762
+ throw new StateQLError("QUERY_FAILED", safeCredentialErrorMessage(error, adapterSource), { retryable: isTransientDatabaseError(error), executed: true });
1722
1763
  }
1723
1764
  finally {
1724
1765
  await closeAdapterQuietly(adapter);
@@ -1845,7 +1886,7 @@ export class StateQL {
1845
1886
  if (error instanceof AdapterExecutionError) {
1846
1887
  throw stoppedStateQLError(error, true);
1847
1888
  }
1848
- throw new StateQLError("QUERY_FAILED", safeCredentialErrorMessage(error, adapterSource), { retryable: true, executed: true });
1889
+ throw new StateQLError("QUERY_FAILED", safeCredentialErrorMessage(error, adapterSource), { retryable: isTransientDatabaseError(error), executed: true });
1849
1890
  }
1850
1891
  finally {
1851
1892
  await closeAdapterQuietly(adapter);
@@ -1943,6 +1984,7 @@ export class StateQL {
1943
1984
  generated_aliases: true,
1944
1985
  multi_row_table_plans: true,
1945
1986
  history_classification: true,
1987
+ actor_display_names: true,
1946
1988
  },
1947
1989
  driver_features: {
1948
1990
  mongodb: {
@@ -1995,6 +2037,10 @@ export class StateQL {
1995
2037
  return this.disconnect();
1996
2038
  case "status":
1997
2039
  return this.status();
2040
+ case "actor.show":
2041
+ return this.showActor();
2042
+ case "actor.set-name":
2043
+ return this.setActorName(batchString(command.name, "name"));
1998
2044
  case "profile.add":
1999
2045
  return this.addProfile(batchString(command.name, "name"), command.target, {
2000
2046
  readOnly: command.read_only ?? true,
@@ -2817,6 +2863,21 @@ export class StateQL {
2817
2863
  throw new StateQLError("INVALID_COMMAND", "Actor ID is required.");
2818
2864
  }
2819
2865
  }
2866
+ validateActorName(value) {
2867
+ if (typeof value !== "string") {
2868
+ throw new StateQLError("INVALID_COMMAND", "Actor name must be a string.");
2869
+ }
2870
+ const name = value.trim();
2871
+ if (!name)
2872
+ throw new StateQLError("INVALID_COMMAND", "Actor name is required.");
2873
+ if ([...name].length > 80) {
2874
+ throw new StateQLError("INVALID_COMMAND", "Actor name cannot exceed 80 characters.");
2875
+ }
2876
+ if (/[\u0000-\u001f\u007f]/u.test(name)) {
2877
+ throw new StateQLError("INVALID_COMMAND", "Actor name cannot contain control characters.");
2878
+ }
2879
+ return name;
2880
+ }
2820
2881
  throwMembershipDenied(session) {
2821
2882
  throw new StateQLError("PERMISSION_DENIED", `Actor "${this.actorId}" is not attached to session "${session.name}".`);
2822
2883
  }
@@ -2984,6 +3045,7 @@ export class StateQL {
2984
3045
  },
2985
3046
  };
2986
3047
  }
3048
+ const actorName = this.store.getActor(session.id, this.actorId).actor_name;
2987
3049
  try {
2988
3050
  const result = await action(session);
2989
3051
  const responseSession = result.session ?? session;
@@ -2991,6 +3053,7 @@ export class StateQL {
2991
3053
  const history = this.store.addHistory({
2992
3054
  sessionId: session.id,
2993
3055
  actorId: this.actorId,
3056
+ actorName,
2994
3057
  origin,
2995
3058
  category,
2996
3059
  internal,
@@ -3025,6 +3088,7 @@ export class StateQL {
3025
3088
  const history = this.store.addHistory({
3026
3089
  sessionId: session.id,
3027
3090
  actorId: this.actorId,
3091
+ actorName,
3028
3092
  origin,
3029
3093
  category,
3030
3094
  internal,
@@ -3057,6 +3121,7 @@ function historyEntry(item) {
3057
3121
  timestamp: item.timestamp,
3058
3122
  session_id: item.session_id,
3059
3123
  actor_id: item.actor_id,
3124
+ actor_name: item.actor_name,
3060
3125
  origin: item.origin,
3061
3126
  category: item.category,
3062
3127
  internal: Boolean(item.internal),
@@ -3070,6 +3135,12 @@ function historyEntry(item) {
3070
3135
  error_code: item.error_code,
3071
3136
  };
3072
3137
  }
3138
+ function actorNameHistoryTarget(value) {
3139
+ if (typeof value !== "string" || /[\u0000-\u001f\u007f]/u.test(value))
3140
+ return undefined;
3141
+ const name = value.trim();
3142
+ return name ? [...name].slice(0, 80).join("") : undefined;
3143
+ }
3073
3144
  const COMMAND_ORIGINS = new Set([
3074
3145
  "legacy",
3075
3146
  "user",
@@ -104,6 +104,7 @@ export interface HistoryRecord {
104
104
  timestamp: string;
105
105
  session_id: string;
106
106
  actor_id: string;
107
+ actor_name: string;
107
108
  origin: CommandOrigin;
108
109
  category: HistoryCategory;
109
110
  internal: number;
@@ -119,6 +120,7 @@ export interface HistoryRecord {
119
120
  export interface SessionMemberRecord {
120
121
  session_id: string;
121
122
  actor_id: string;
123
+ actor_name: string;
122
124
  attached_at: string;
123
125
  }
124
126
  export declare class StateStore {
@@ -137,6 +139,8 @@ export declare class StateStore {
137
139
  isSessionMember(sessionId: string, actorId: string): boolean;
138
140
  linkActor(sessionId: string, requestingActorId: string, actorId: string): "linked" | "already_linked" | "actor_conflict" | "denied";
139
141
  unlinkActor(sessionId: string, requestingActorId: string, actorId: string): "unlinked" | "not_linked" | "owns_transaction" | "denied";
142
+ getActor(sessionId: string, actorId: string): SessionMemberRecord | undefined;
143
+ setActorName(sessionId: string, actorId: string, actorName: string): SessionMemberRecord | undefined;
140
144
  listActors(sessionId: string): SessionMemberRecord[];
141
145
  resolveActor(actorId: string): SessionRecord | undefined;
142
146
  getSession(idOrName: string): SessionRecord | undefined;
@@ -299,6 +303,7 @@ export declare class StateStore {
299
303
  addHistory(input: {
300
304
  sessionId: string;
301
305
  actorId: string;
306
+ actorName?: string;
302
307
  origin?: CommandOrigin;
303
308
  category?: HistoryCategory;
304
309
  internal?: boolean;
package/dist/src/store.js CHANGED
@@ -113,16 +113,16 @@ export class StateStore {
113
113
  }
114
114
  if (created) {
115
115
  this.db
116
- .prepare(`INSERT INTO session_members(session_id, actor_id, attached_at)
117
- VALUES (?, ?, ?)`)
118
- .run(row.id, actorId, timestamp);
116
+ .prepare(`INSERT INTO session_members(session_id, actor_id, actor_name, attached_at)
117
+ VALUES (?, ?, ?, ?)`)
118
+ .run(row.id, actorId, actorId, timestamp);
119
119
  }
120
120
  else if (ensureLegacyMembership) {
121
121
  this.db
122
122
  .prepare(`INSERT OR IGNORE INTO session_members
123
- (session_id, actor_id, attached_at)
124
- VALUES (?, ?, ?)`)
125
- .run(row.id, actorId, timestamp);
123
+ (session_id, actor_id, actor_name, attached_at)
124
+ VALUES (?, ?, ?, ?)`)
125
+ .run(row.id, actorId, actorId, timestamp);
126
126
  }
127
127
  this.db.exec("COMMIT");
128
128
  return this.getSession(row.id);
@@ -167,9 +167,9 @@ export class StateStore {
167
167
  if (this.isSessionMember(row.id, identity))
168
168
  continue;
169
169
  this.db
170
- .prepare(`INSERT INTO session_members(session_id, actor_id, attached_at)
171
- VALUES (?, ?, ?)`)
172
- .run(row.id, identity, timestamp);
170
+ .prepare(`INSERT INTO session_members(session_id, actor_id, actor_name, attached_at)
171
+ VALUES (?, ?, ?, ?)`)
172
+ .run(row.id, identity, identity, timestamp);
173
173
  }
174
174
  const session = this.getSessionByName(name);
175
175
  if (!session)
@@ -204,9 +204,9 @@ export class StateStore {
204
204
  return existing.id === sessionId ? "already_linked" : "actor_conflict";
205
205
  }
206
206
  this.db
207
- .prepare(`INSERT INTO session_members(session_id, actor_id, attached_at)
208
- VALUES (?, ?, ?)`)
209
- .run(sessionId, actorId, this.now().toISOString());
207
+ .prepare(`INSERT INTO session_members(session_id, actor_id, actor_name, attached_at)
208
+ VALUES (?, ?, ?, ?)`)
209
+ .run(sessionId, actorId, actorId, this.now().toISOString());
210
210
  this.db.exec("COMMIT");
211
211
  return "linked";
212
212
  }
@@ -243,6 +243,19 @@ export class StateStore {
243
243
  throw error;
244
244
  }
245
245
  }
246
+ getActor(sessionId, actorId) {
247
+ return this.db
248
+ .prepare(`SELECT * FROM session_members
249
+ WHERE session_id = ? AND actor_id = ?`)
250
+ .get(sessionId, actorId);
251
+ }
252
+ setActorName(sessionId, actorId, actorName) {
253
+ return this.db
254
+ .prepare(`UPDATE session_members SET actor_name = ?
255
+ WHERE session_id = ? AND actor_id = ?
256
+ RETURNING *`)
257
+ .get(actorName, sessionId, actorId);
258
+ }
246
259
  listActors(sessionId) {
247
260
  return this.db
248
261
  .prepare(`SELECT * FROM session_members
@@ -943,10 +956,10 @@ export class StateStore {
943
956
  const insert = (id) => {
944
957
  this.db
945
958
  .prepare(`INSERT INTO history
946
- (id, timestamp, session_id, actor_id, origin, category, internal, command, sql, target, handle,
959
+ (id, timestamp, session_id, actor_id, actor_name, origin, category, internal, command, sql, target, handle,
947
960
  executed, cached, success, error_code)
948
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
949
- .run(id, this.now().toISOString(), input.sessionId, input.actorId, input.origin ?? "legacy", input.category ?? "management", input.internal ? 1 : 0, input.command, boundedHistorySql(input.sql), input.target?.slice(0, 1024) ?? null, input.handle ?? null, input.executed ? 1 : 0, input.cached ? 1 : 0, input.success ? 1 : 0, input.errorCode ?? null);
961
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
962
+ .run(id, this.now().toISOString(), input.sessionId, input.actorId, input.actorName ?? this.getActor(input.sessionId, input.actorId)?.actor_name ?? input.actorId, input.origin ?? "legacy", input.category ?? "management", input.internal ? 1 : 0, input.command, boundedHistorySql(input.sql), input.target?.slice(0, 1024) ?? null, input.handle ?? null, input.executed ? 1 : 0, input.cached ? 1 : 0, input.success ? 1 : 0, input.errorCode ?? null);
950
963
  };
951
964
  const id = input.id ?? this.insertWithRandomId("cmd", "history", insert);
952
965
  if (input.id !== undefined)
@@ -1,4 +1,4 @@
1
- import { BSON } from "mongodb";
1
+ import { BSON } from "bson";
2
2
  import { StateQLError } from "./errors.js";
3
3
  export function quoteIdentifier(name, driver) {
4
4
  if (!name || name.length > 500 || name.includes("\0"))
@@ -83,6 +83,7 @@ export interface HistoryEntry {
83
83
  timestamp: string;
84
84
  session_id: string;
85
85
  actor_id: string;
86
+ actor_name: string;
86
87
  origin: CommandOrigin;
87
88
  category: HistoryCategory;
88
89
  internal: boolean;
@@ -107,6 +108,7 @@ export interface StateQLSnapshot {
107
108
  status: string;
108
109
  };
109
110
  actor_id: string;
111
+ actor_name: string;
110
112
  connection: {
111
113
  connection_id: string;
112
114
  /** Generated display identity; optional for older snapshot producers. */
@@ -345,7 +347,7 @@ export interface MongoPlanOptions extends ExecutionOptions {
345
347
  allowUnbounded?: boolean;
346
348
  allowDestructive?: boolean;
347
349
  }
348
- export type BatchCommandName = "connect" | "disconnect" | "status" | "profile.add" | "profile.list" | "profile.show" | "profile.remove" | "profile.update" | "session.start" | "session.list" | "session.show" | "session.summary" | "session.close" | "query" | "filter" | "exec" | "show" | "rows" | "count" | "columns" | "alias.set" | "inspect" | "transaction.begin" | "transaction.status" | "transaction.commit" | "transaction.rollback" | "plan" | "mongo.query" | "mongo.exec" | "mongo.plan" | "redis.query" | "redis.exec" | "redis.plan" | "objects.list" | "object.describe" | "apply" | "history" | "receipt" | "doctor" | "purge" | "capabilities";
350
+ export type BatchCommandName = "connect" | "disconnect" | "status" | "actor.show" | "actor.set-name" | "profile.add" | "profile.list" | "profile.show" | "profile.remove" | "profile.update" | "session.start" | "session.list" | "session.show" | "session.summary" | "session.close" | "query" | "filter" | "exec" | "show" | "rows" | "count" | "columns" | "alias.set" | "inspect" | "transaction.begin" | "transaction.status" | "transaction.commit" | "transaction.rollback" | "plan" | "mongo.query" | "mongo.exec" | "mongo.plan" | "redis.query" | "redis.exec" | "redis.plan" | "objects.list" | "object.describe" | "apply" | "history" | "receipt" | "doctor" | "purge" | "capabilities";
349
351
  export interface BatchCommand {
350
352
  command: BatchCommandName;
351
353
  target?: string;
@@ -433,6 +435,7 @@ export interface StatusData {
433
435
  session_id: string;
434
436
  session_name: string;
435
437
  actor_id: string;
438
+ actor_name: string;
436
439
  connection: StatusConnectionData | null;
437
440
  transaction: TransactionReferenceData | null;
438
441
  state_version: string | null;
@@ -449,6 +452,7 @@ export interface ActorUnlinkData {
449
452
  }
450
453
  export interface ActorData {
451
454
  actor_id: string;
455
+ actor_name: string;
452
456
  attached_at: string;
453
457
  }
454
458
  export interface ActorsData {
@@ -6,6 +6,7 @@ export declare function parseJson<T>(value: string, context: string, validate?:
6
6
  export declare function isSqlParameters(value: unknown): value is SqlParameters;
7
7
  export declare function isRows(value: unknown): value is Row[];
8
8
  export declare function isColumns(value: unknown): value is Column[];
9
+ export declare function isRecord(value: unknown): value is Record<string, unknown>;
9
10
  export declare function redact(value: string): string;
10
11
  export declare function compactRows(rows: Row[], maxCellCharacters: number): Row[];
11
12
  export declare function toJsonSafe<T>(value: T): T;
package/dist/src/util.js CHANGED
@@ -49,7 +49,7 @@ export function isColumns(value) {
49
49
  typeof column.name === "string" &&
50
50
  typeof column.type === "string");
51
51
  }
52
- function isRecord(value) {
52
+ export function isRecord(value) {
53
53
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
54
54
  }
55
55
  function corruptedState(context) {
package/docs/agents.md ADDED
@@ -0,0 +1,72 @@
1
+ # Agent guide
2
+
3
+ [StateQL](../README.md) · [Agents](agents.md) · [Connections](connections.md) · [CLI](cli.md) · [Results](results.md) · [Writes](writes.md) · [Batch](batch.md) · [Databases](databases.md) · [Library](library.md)
4
+
5
+ The minimum an agent needs to query a database with `stql`. Read the other pages
6
+ only for the topic at hand.
7
+
8
+ ## Setup
9
+
10
+ ```bash
11
+ export STQL_SESSION=task-42 # keeps handles and aliases across calls
12
+ stql connect ./app.sqlite # read-only by default
13
+ stql connect --env DATABASE_URL # remote URL from an environment variable
14
+ ```
15
+
16
+ ## Read
17
+
18
+ ```bash
19
+ stql objects table --search user # find tables
20
+ stql object table users # table DDL
21
+ stql query "SELECT id, name FROM users WHERE status = ? ORDER BY id" --param active
22
+ ```
23
+
24
+ ```json
25
+ {"ok":true,"handle":"katcitg6un","total":333,"next_offset":5,"columns":["id","name"],"rows":[[2,"Ada"],[3,"Grace"],[5,"Linus"],[6,"Alan"],[8,"Edsger"]]}
26
+ ```
27
+
28
+ - Rows are arrays in `columns` order. If rows have different keys, they stay
29
+ objects and `columns` is omitted.
30
+ - `next_offset` is present only when more rows exist.
31
+ - Null fields and false `cached`/`duplicate` flags are omitted.
32
+ - Long cells come back as `{"type":"text","length":N,"preview":"..."}`.
33
+ - `objects` uses the same `columns` + arrays shape.
34
+ - `rows`, `count`, and `columns` do not repeat the handle you passed.
35
+ - Result handles are short, stable aliases. Full `q_...` IDs also work.
36
+ - Writes return `handle`, `statement_type`, `affected_rows`, `status`, and
37
+ `state_version_after`.
38
+
39
+ ## Reuse a result without querying again
40
+
41
+ ```bash
42
+ stql rows katcitg6un --offset 5 --limit 20
43
+ stql count katcitg6un
44
+ stql filter katcitg6un "name LIKE ?" --param "A%"
45
+ stql export katcitg6un --output users.csv
46
+ ```
47
+
48
+ ## Save tokens
49
+
50
+ - Select only the columns you need, and add `ORDER BY` and `LIMIT`.
51
+ - Use `--preview-rows 0` when you need only the handle and `total`.
52
+ - Use `stql pipe` to run several commands in one call:
53
+
54
+ ```bash
55
+ printf '%s\n' \
56
+ '{"command":"query","sql":"SELECT id, email FROM users ORDER BY id","as":"users"}' \
57
+ '{"command":"count","handle":"users"}' | stql pipe
58
+ ```
59
+
60
+ ## Errors
61
+
62
+ Errors are `{"ok":false,"error":{"code":...,"message":...}}`. Follow
63
+ `suggested_action` or `override_flag` when present. Retry only when
64
+ `retryable` is true (lost connection, deadlock, lock timeout). SQL syntax errors
65
+ give the line, column, and nearby text. Do not replay a write that
66
+ returned `OUTCOME_UNKNOWN` until you have checked the database.
67
+
68
+ ## Writes
69
+
70
+ Connect with `--read-write`. Use `stql exec` with `--idempotency-key KEY` for
71
+ retryable writes. Writes without `WHERE` need `--allow-unbounded`, and
72
+ destructive statements need `--allow-destructive`. See [write safety](writes.md).
package/docs/batch.md ADDED
@@ -0,0 +1,49 @@
1
+ # Batch and pipes
2
+
3
+ [StateQL](../README.md) · [Agents](agents.md) · [Connections](connections.md) · [CLI](cli.md) · [Results](results.md) · [Writes](writes.md) · [Batch](batch.md) · [Databases](databases.md) · [Library](library.md)
4
+
5
+ `batch` reads a JSON array from a `.json` file or JSONL from a `.jsonl` file.
6
+ `pipe` reads JSONL from standard input. Commands run sequentially and stop on
7
+ the first error unless `--continue-on-error` is set. Output defaults to one
8
+ compact `agent` JSON object per line.
9
+
10
+ Pipe commands directly:
11
+
12
+ ```bash
13
+ printf '%s\n' \
14
+ '{"command":"query","sql":"SELECT id, email FROM users ORDER BY id","as":"users"}' \
15
+ '{"command":"filter","handle":"users","where":"email LIKE ?","params":["%@example.com"],"as":"example_users"}' \
16
+ '{"command":"rows","handle":"example_users","limit":10}' |
17
+ stql pipe
18
+ ```
19
+
20
+ Or save a JSON array as `commands.json`:
21
+
22
+ ```json
23
+ [
24
+ {
25
+ "command": "exec",
26
+ "sql": "UPDATE jobs SET claimed = 1 WHERE id = ?",
27
+ "params": [42],
28
+ "idempotency_key": "claim-job-42"
29
+ },
30
+ {
31
+ "command": "query",
32
+ "sql": "SELECT * FROM jobs WHERE id = ?",
33
+ "params": [42]
34
+ }
35
+ ]
36
+ ```
37
+
38
+ ```bash
39
+ stql batch commands.json
40
+ ```
41
+
42
+ Batch fields use snake case. Supported command names match CLI paths, such as
43
+ `actor.show`, `actor.set-name`, `filter`, `transaction.begin`, `session.summary`,
44
+ `alias.set`, `plan`, and `apply`. `actor.set-name` takes the display name in the
45
+ `name` field. Query commands may set `preview_rows` from 0 to 200. Native MongoDB
46
+ batches use `mongo.query`, `mongo.exec`, or `mongo.plan` with the command object
47
+ in `mongo`; the same cache, replay, idempotency, safety, and timeout fields
48
+ apply. Database commands may set `timeout_ms`; otherwise they use the 30-second
49
+ default.