@sixb/client 0.1.11 → 0.1.13

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 (98) hide show
  1. package/dist/agent-streams.d.ts +7 -2
  2. package/dist/agent-streams.d.ts.map +1 -1
  3. package/dist/api.d.ts +8 -1
  4. package/dist/api.d.ts.map +1 -1
  5. package/dist/base-url.d.ts +2 -0
  6. package/dist/base-url.d.ts.map +1 -0
  7. package/dist/browser.js +7 -7
  8. package/dist/browser.js.map +3 -3
  9. package/dist/{chunk-y4g6jrvs.js → chunk-1d0xnr6p.js} +38 -7
  10. package/dist/chunk-1d0xnr6p.js.map +10 -0
  11. package/dist/{chunk-f4qeqxz2.js → chunk-50rkzhcy.js} +23 -30
  12. package/dist/chunk-50rkzhcy.js.map +10 -0
  13. package/dist/{chunk-65mmaq7r.js → chunk-6k1hzwk1.js} +13 -11
  14. package/dist/chunk-6k1hzwk1.js.map +17 -0
  15. package/dist/{chunk-7bv57jcq.js → chunk-hdgztpzs.js} +372 -70
  16. package/dist/chunk-hdgztpzs.js.map +19 -0
  17. package/dist/{chunk-tyym13kq.js → chunk-jh4ts8mt.js} +3 -1
  18. package/dist/chunk-jh4ts8mt.js.map +10 -0
  19. package/dist/{chunk-qaacaq2e.js → chunk-nkx0fxxn.js} +6 -4
  20. package/dist/chunk-nkx0fxxn.js.map +10 -0
  21. package/dist/{chunk-65bdf9vw.js → chunk-tgyh8wz9.js} +7 -6
  22. package/dist/chunk-tgyh8wz9.js.map +12 -0
  23. package/dist/chunk-ys86w6hc.js +277 -0
  24. package/dist/chunk-ys86w6hc.js.map +12 -0
  25. package/dist/client-authority.d.ts +4 -0
  26. package/dist/client-authority.d.ts.map +1 -1
  27. package/dist/connectors/queries.d.ts.map +1 -1
  28. package/dist/events-builder.d.ts +2 -2
  29. package/dist/events-builder.d.ts.map +1 -1
  30. package/dist/events-transport.d.ts +4 -1
  31. package/dist/events-transport.d.ts.map +1 -1
  32. package/dist/generated/@tanstack/react-query.gen.d.ts +1555 -366
  33. package/dist/generated/@tanstack/react-query.gen.d.ts.map +1 -1
  34. package/dist/generated/index.d.ts +2 -2
  35. package/dist/generated/index.d.ts.map +1 -1
  36. package/dist/generated/sdk.gen.d.ts +9 -1
  37. package/dist/generated/sdk.gen.d.ts.map +1 -1
  38. package/dist/generated/types.gen.d.ts +594 -91
  39. package/dist/generated/types.gen.d.ts.map +1 -1
  40. package/dist/hooks.js +44 -12
  41. package/dist/hooks.js.map +6 -6
  42. package/dist/index.d.ts +2 -0
  43. package/dist/index.d.ts.map +1 -1
  44. package/dist/index.js +23 -10
  45. package/dist/index.js.map +1 -1
  46. package/dist/logs-builder.d.ts +1 -1
  47. package/dist/logs-builder.d.ts.map +1 -1
  48. package/dist/logs-transport.d.ts +4 -1
  49. package/dist/logs-transport.d.ts.map +1 -1
  50. package/dist/logs.js +4 -4
  51. package/dist/models.d.ts +2 -1
  52. package/dist/models.d.ts.map +1 -1
  53. package/dist/models.js +7 -3
  54. package/dist/models.js.map +1 -1
  55. package/dist/query-hooks.d.ts +3 -21
  56. package/dist/query-hooks.d.ts.map +1 -1
  57. package/dist/query.d.ts +2 -4
  58. package/dist/query.d.ts.map +1 -1
  59. package/dist/query.js +4 -4
  60. package/dist/session.d.ts +56 -0
  61. package/dist/session.d.ts.map +1 -0
  62. package/dist/useAgentActivityStream.d.ts +3 -0
  63. package/dist/useAgentActivityStream.d.ts.map +1 -1
  64. package/dist/useAgentRunStream.d.ts +4 -1
  65. package/dist/useAgentRunStream.d.ts.map +1 -1
  66. package/dist/ws-socket.d.ts +3 -0
  67. package/dist/ws-socket.d.ts.map +1 -1
  68. package/package.json +2 -2
  69. package/src/agent-streams.ts +11 -4
  70. package/src/api.ts +37 -32
  71. package/src/base-url.ts +30 -0
  72. package/src/browser.ts +1 -1
  73. package/src/client-authority.ts +19 -0
  74. package/src/events-builder.ts +5 -9
  75. package/src/events-transport.ts +6 -2
  76. package/src/generated/@tanstack/react-query.gen.ts +62 -0
  77. package/src/generated/index.ts +13 -0
  78. package/src/generated/sdk.gen.ts +398 -68
  79. package/src/generated/types.gen.ts +735 -87
  80. package/src/index.ts +13 -1
  81. package/src/logs-builder.ts +2 -2
  82. package/src/logs-transport.ts +6 -2
  83. package/src/models.ts +4 -2
  84. package/src/query-hooks.ts +2 -17
  85. package/src/query.ts +9 -12
  86. package/src/session.ts +316 -0
  87. package/src/useAgentActivityStream.ts +6 -2
  88. package/src/useAgentRunStream.ts +7 -3
  89. package/src/ws-socket.ts +62 -5
  90. package/dist/chunk-65bdf9vw.js.map +0 -12
  91. package/dist/chunk-65mmaq7r.js.map +0 -17
  92. package/dist/chunk-65zz479s.js +0 -23
  93. package/dist/chunk-65zz479s.js.map +0 -10
  94. package/dist/chunk-7bv57jcq.js.map +0 -19
  95. package/dist/chunk-f4qeqxz2.js.map +0 -10
  96. package/dist/chunk-qaacaq2e.js.map +0 -10
  97. package/dist/chunk-tyym13kq.js.map +0 -10
  98. package/dist/chunk-y4g6jrvs.js.map +0 -10
package/src/index.ts CHANGED
@@ -13,6 +13,18 @@ export * from "./file"
13
13
  export * from "./generated"
14
14
  export { client } from "./generated/client.gen"
15
15
  export * from "./logs"
16
-
17
16
  // Framework UI models and adapters
18
17
  export * from "./models"
18
+ export type {
19
+ SixbDeviceLogin,
20
+ SixbSessionOptions,
21
+ SixbSessionRequestOptions,
22
+ SixbSessionStore,
23
+ SixbSessionTokens,
24
+ } from "./session"
25
+ export {
26
+ getSixbSessionAccessToken,
27
+ SixbSessionEndedError,
28
+ signOutSixbSession,
29
+ startSixbDeviceLogin,
30
+ } from "./session"
@@ -44,7 +44,7 @@ export interface SixbLogsPage {
44
44
  }
45
45
 
46
46
  export interface SixbLogsClientOptions {
47
- /** HTTP client override for reads. Its base URL is also used by the cookie-authenticated WS. */
47
+ /** HTTP client override for reads. The WebSocket uses its base URL and credential too. */
48
48
  readonly client?: Client
49
49
  }
50
50
 
@@ -100,7 +100,7 @@ class LogsBuilderImpl implements RunScopedLogsBuilder {
100
100
  afterCursor: options?.afterCursor,
101
101
  reconnect: options?.reconnect,
102
102
  reconnectDelayMs: options?.reconnectDelayMs,
103
- baseUrl: transportClient.getConfig().baseUrl,
103
+ client: transportClient,
104
104
  onLog: handler,
105
105
  onError: options?.onError,
106
106
  onReset: options?.onReset,
@@ -5,6 +5,7 @@ import {
5
5
  type SixbRunKind,
6
6
  type StoredLogLine,
7
7
  } from "@sixb/core/logging"
8
+ import type { Client } from "./generated/client"
8
9
  import {
9
10
  createReconnectingSocket,
10
11
  createSixbWebSocketUrl,
@@ -20,8 +21,10 @@ export interface LogSocketOptions {
20
21
  readonly afterCursor?: string
21
22
  readonly reconnect?: boolean
22
23
  readonly reconnectDelayMs?: number
23
- /** API origin override. Authentication uses the browser session cookie. */
24
+ /** Override the API base url. Defaults to `client`'s, then the global client config. */
24
25
  readonly baseUrl?: string
26
+ /** The client whose API and credential the socket uses. Defaults to the package's shared client. */
27
+ readonly client?: Client
25
28
  readonly onLog: (line: StoredLogLine) => void
26
29
  readonly onError?: (error: string) => void
27
30
  readonly onReset?: (cursor?: string) => void
@@ -42,7 +45,8 @@ export function createLogSocket(options: LogSocketOptions): LogSocket {
42
45
  let latestCursor = options.afterCursor
43
46
 
44
47
  return createReconnectingSocket({
45
- url: createSixbLogsWebSocketUrl(options.baseUrl),
48
+ url: createSixbLogsWebSocketUrl(options.baseUrl ?? options.client?.getConfig().baseUrl),
49
+ client: options.client,
46
50
  reconnect: options.reconnect,
47
51
  reconnectDelayMs: options.reconnectDelayMs,
48
52
  connectionErrorMessage: "Log websocket connection failed.",
package/src/models.ts CHANGED
@@ -24,7 +24,8 @@ export interface RelationshipEdge {
24
24
  }
25
25
 
26
26
  export interface ActionParam {
27
- type: "string" | "number" | "boolean" | "fileRef"
27
+ /** `userRef` params take a user reference `{ type: "user", id }`. */
28
+ type: "string" | "number" | "boolean" | "fileRef" | "userRef"
28
29
  required?: boolean
29
30
  nullable?: boolean
30
31
  description?: string
@@ -151,12 +152,13 @@ function parseLocation(
151
152
  return undefined
152
153
  }
153
154
 
154
- function inferPrimitiveType(schema: unknown): "string" | "number" | "boolean" | "fileRef" {
155
+ function inferPrimitiveType(schema: unknown): ActionParam["type"] {
155
156
  if (typeof schema === "string") {
156
157
  if (schema === "integer" || schema === "double") return "number"
157
158
  if (schema === "decimal") return "string"
158
159
  if (schema === "boolean") return "boolean"
159
160
  if (schema === "fileRef") return "fileRef"
161
+ if (schema === "userRef") return "userRef"
160
162
  return "string"
161
163
  }
162
164
 
@@ -575,23 +575,8 @@ function isGeneratedObjectRead(query: { readonly queryKey: readonly unknown[] })
575
575
  // position, constraining on its overloaded members, or extracting via
576
576
  // `ReturnType` all overflow TypeScript's recursion depth on real ontologies.
577
577
 
578
- /**
579
- * Result row type of a built query, taken from its `first()` terminal.
580
- * Rebuilt as an anonymous structural type: relating the generic `TwinObject`
581
- * reference itself in deep contexts (e.g. `rows.map(...)` callbacks) can
582
- * overflow TypeScript's recursion limits.
583
- */
584
- type BuiltRow<TBuilt> = TBuilt extends { first(): Promise<infer TRow> }
585
- ? NonNullable<TRow> extends { objectTypeId: infer TObjectTypeId; properties: infer TProperties }
586
- ? {
587
- primaryId: string
588
- objectTypeId: TObjectTypeId
589
- properties: TProperties
590
- createdAt: Date
591
- updatedAt: Date
592
- } & (NonNullable<TRow> extends { links: infer TLinks } ? { links: TLinks } : unknown)
593
- : never
594
- : never
578
+ /** Result row type of a built query, `.links` included, as its `first()` terminal returns it. */
579
+ type BuiltRow<TBuilt> = TBuilt extends { first(): Promise<infer TRow | null> } ? TRow : never
595
580
 
596
581
  /**
597
582
  * Common TanStack passthrough options. For anything beyond these (`select`,
package/src/query.ts CHANGED
@@ -6,7 +6,6 @@
6
6
  * are validated server-side; failures surface as `SixbQueryError`.
7
7
  */
8
8
 
9
- import type { SixbObjectTypeMap } from "@sixb/core/ontology"
10
9
  import type {
11
10
  ObjectQuery,
12
11
  ObjectQueryBuilder,
@@ -15,6 +14,7 @@ import type {
15
14
  ObjectQueryExecutorFacetRequest,
16
15
  ObjectQueryExecutorLinkValue,
17
16
  ObjectQueryExecutorRow,
17
+ ObjectQueryRow,
18
18
  ObjectTypeWithPropertyTokens,
19
19
  } from "@sixb/core/query"
20
20
  import { createObjectQueryBuilder } from "@sixb/core/query"
@@ -44,15 +44,10 @@ export interface SixbQueryClientOptions {
44
44
  client?: Client
45
45
  }
46
46
 
47
- // Value types are typed as "none registered": custom value-type refs resolve
48
- // like a runtime without them, and the empty tuple keeps property-value
49
- // inference shallow enough for TypeScript's recursion limits.
50
- type ClientRegisteredObjectTypes<TObjectType extends ObjectTypeWithPropertyTokens> =
51
- | TObjectType
52
- | Extract<SixbObjectTypeMap[keyof SixbObjectTypeMap], ObjectTypeWithPropertyTokens>
53
-
54
- export type ClientObjectQueryBuilder<TObjectType extends ObjectTypeWithPropertyTokens> =
55
- ObjectQueryBuilder<TObjectType, ClientRegisteredObjectTypes<TObjectType>, readonly []>
47
+ export type ClientObjectQueryBuilder<
48
+ TObjectType extends ObjectTypeWithPropertyTokens,
49
+ TRow = ObjectQueryRow<TObjectType>,
50
+ > = ObjectQueryBuilder<TObjectType, TRow>
56
51
 
57
52
  export function objects<TObjectType extends ObjectTypeWithPropertyTokens>(
58
53
  objectType: TObjectType,
@@ -60,7 +55,7 @@ export function objects<TObjectType extends ObjectTypeWithPropertyTokens>(
60
55
  ): { query: () => ClientObjectQueryBuilder<TObjectType> } {
61
56
  return {
62
57
  query: () =>
63
- createObjectQueryBuilder<TObjectType, ClientRegisteredObjectTypes<TObjectType>, readonly []>({
58
+ createObjectQueryBuilder<TObjectType>({
64
59
  query: { kind: "start", objectTypeId: objectType.id },
65
60
  executor: createHttpQueryExecutor(options?.client),
66
61
  }),
@@ -75,10 +70,11 @@ export function createHttpQueryExecutor(client?: Client): ObjectQueryExecutor {
75
70
  const callOptions = { client, responseStyle: "fields", throwOnError: false } as const
76
71
 
77
72
  return {
78
- async list(query: ObjectQuery, options?: { includeTotal?: boolean }) {
73
+ async list(query: ObjectQuery, options?: { includeTotal?: boolean; signal?: AbortSignal }) {
79
74
  const { data, error } = await queryObjects({
80
75
  ...callOptions,
81
76
  body: { query: toWireQuery(query), includeTotal: options?.includeTotal },
77
+ signal: options?.signal,
82
78
  })
83
79
  if (error || !data) throw toSixbQueryError(error)
84
80
  return {
@@ -126,6 +122,7 @@ export function createHttpQueryExecutor(client?: Client): ObjectQueryExecutor {
126
122
  // builder types `links` precisely; here it flows through as runtime data.
127
123
  function reviveQueryRow(row: ObjectQueryObject): ObjectQueryExecutorRow {
128
124
  const revived: ObjectQueryExecutorRow = {
125
+ ...(row.score === undefined ? {} : { score: row.score }),
129
126
  primaryId: row.primaryId,
130
127
  objectTypeId: row.objectTypeId,
131
128
  properties: row.properties,
package/src/session.ts ADDED
@@ -0,0 +1,316 @@
1
+ import { normalizeSixbApiBaseUrl } from "./base-url"
2
+
3
+ /** A native client's session tokens. Keep them in secure storage and never log them. */
4
+ export interface SixbSessionTokens {
5
+ readonly accessToken: string
6
+ readonly refreshToken: string
7
+ /** ISO time the access token expires. */
8
+ readonly accessExpiresAt: string
9
+ }
10
+
11
+ /** Where a native client keeps its session between launches, such as a 0600 file. */
12
+ export interface SixbSessionStore {
13
+ load(): Promise<SixbSessionTokens | null> | SixbSessionTokens | null
14
+ save(tokens: SixbSessionTokens): Promise<void> | void
15
+ clear(): Promise<void> | void
16
+ }
17
+
18
+ /** The session was signed out, revoked, or left unused past its idle timeout. Sign in again. */
19
+ export class SixbSessionEndedError extends Error {
20
+ override readonly name = "SixbSessionEndedError"
21
+ }
22
+
23
+ export interface SixbSessionRequestOptions {
24
+ readonly baseUrl: string
25
+ readonly fetch?: typeof fetch
26
+ }
27
+
28
+ export interface SixbSessionOptions extends SixbSessionRequestOptions {
29
+ readonly store: SixbSessionStore
30
+ /** Called once when the session ends; the store has been cleared. Sign the user in again. */
31
+ readonly onSessionEnded?: () => void
32
+ }
33
+
34
+ export interface SixbDeviceLogin {
35
+ /** Show this to the user; the approval page shows the same code. */
36
+ readonly userCode: string
37
+ /** Open this in a browser. It carries the code, so the user only confirms. */
38
+ readonly verificationUriComplete: string
39
+ readonly verificationUri: string
40
+ readonly expiresAt: string
41
+ /** Poll until the user approves in the browser, then return the new session's tokens. */
42
+ complete(options?: { readonly signal?: AbortSignal }): Promise<SixbSessionTokens>
43
+ }
44
+
45
+ // Refresh this long before the access token expires, so no request goes out with one about to lapse.
46
+ const REFRESH_MARGIN_MS = 60_000
47
+
48
+ // One refresh per store at a time: concurrent requests share it, since each refresh retires the
49
+ // refresh token the others would present.
50
+ const refreshing = new WeakMap<SixbSessionStore, Promise<SixbSessionTokens>>()
51
+
52
+ /** Ask the API to sign this device in. Open `verificationUriComplete`, then await `complete()`. */
53
+ export async function startSixbDeviceLogin(
54
+ options: SixbSessionRequestOptions & { readonly clientName: string }
55
+ ): Promise<SixbDeviceLogin> {
56
+ const post = sessionRequester(options)
57
+ const response = await post("/api/auth/device-authorizations", {
58
+ clientName: options.clientName,
59
+ })
60
+ if (!response.ok) throw await requestError(response, "start device login")
61
+
62
+ const body = asRecord(await response.json())
63
+ const deviceCode = nonblank(body.deviceCode)
64
+ const userCode = nonblank(body.userCode)
65
+ const verificationUri = nonblank(body.verificationUri)
66
+ const verificationUriComplete = nonblank(body.verificationUriComplete)
67
+ const expiresAt = nonblank(body.expiresAt)
68
+ const interval = body.interval
69
+ if (
70
+ !deviceCode ||
71
+ !userCode ||
72
+ !verificationUri ||
73
+ !verificationUriComplete ||
74
+ !expiresAt ||
75
+ !Number.isFinite(Date.parse(expiresAt)) ||
76
+ typeof interval !== "number" ||
77
+ !Number.isFinite(interval)
78
+ ) {
79
+ throw new Error("[SixbClient] The Sixb API returned an invalid device login.")
80
+ }
81
+ // The user approves on this page while signed in, so it must be the API the device signs in to.
82
+ if (new URL(verificationUriComplete).origin !== new URL(apiBase(options.baseUrl)).origin) {
83
+ throw new Error("[SixbClient] The device login page is not on the Sixb API origin.")
84
+ }
85
+
86
+ const intervalMs = Math.max(1, Math.min(10, interval)) * 1000
87
+ return {
88
+ userCode,
89
+ verificationUri,
90
+ verificationUriComplete,
91
+ expiresAt,
92
+ async complete({ signal } = {}) {
93
+ while (Date.now() < Date.parse(expiresAt)) {
94
+ signal?.throwIfAborted()
95
+ const poll = await post("/api/auth/device-authorizations/token", { deviceCode }, signal)
96
+ if (!poll.ok) throw await requestError(poll, "complete device login")
97
+ const result = asRecord(await poll.json())
98
+ if (result.status === "approved") return parseSessionTokens(result)
99
+ if (result.status === "denied") throw new Error("[SixbClient] Device login was denied.")
100
+ if (result.status === "expired") break
101
+ if (result.status !== "pending") {
102
+ throw new Error("[SixbClient] The Sixb API returned an unknown device login status.")
103
+ }
104
+ await sleep(intervalMs, signal)
105
+ }
106
+ throw new Error("[SixbClient] Device login expired. Start it again.")
107
+ },
108
+ }
109
+ }
110
+
111
+ /** Trade a refresh token for new tokens. Throws `SixbSessionEndedError` when the session is gone. */
112
+ async function refreshSixbSession(
113
+ options: SixbSessionRequestOptions & { readonly refreshToken: string }
114
+ ): Promise<SixbSessionTokens> {
115
+ const post = sessionRequester(options)
116
+ const response = await post("/api/auth/refresh", { refreshToken: options.refreshToken })
117
+ if (response.status === 401) throw sessionEnded()
118
+ if (!response.ok) throw await requestError(response, "refresh the session")
119
+ return parseSessionTokens(await response.json())
120
+ }
121
+
122
+ /**
123
+ * The stored session's access token, refreshed and saved first when it is about to expire. Null
124
+ * when the store holds no session. A session that has ended clears the store and throws
125
+ * `SixbSessionEndedError`.
126
+ */
127
+ export async function getSixbSessionAccessToken(
128
+ options: SixbSessionOptions
129
+ ): Promise<string | null> {
130
+ const tokens = await options.store.load()
131
+ if (!tokens) return null
132
+ const remainingMs = Date.parse(tokens.accessExpiresAt) - Date.now()
133
+ if (remainingMs > REFRESH_MARGIN_MS) return tokens.accessToken
134
+ try {
135
+ return (await renewSession(options, tokens)).accessToken
136
+ } catch (error) {
137
+ // An early refresh that fails for a transient reason (offline, server error) must not fail a
138
+ // request the current token can still make.
139
+ if (!(error instanceof SixbSessionEndedError) && remainingMs > 0) return tokens.accessToken
140
+ throw error
141
+ }
142
+ }
143
+
144
+ /** End the stored session on the server, then clear the store. */
145
+ export async function signOutSixbSession(options: SixbSessionOptions): Promise<void> {
146
+ let accessToken: string | null
147
+ try {
148
+ accessToken = await getSixbSessionAccessToken(options)
149
+ } catch (error) {
150
+ // A session that already ended leaves nothing to revoke.
151
+ if (error instanceof SixbSessionEndedError) return
152
+ throw error
153
+ }
154
+ if (accessToken) {
155
+ const response = await (options.fetch ?? globalThis.fetch)(
156
+ `${apiBase(options.baseUrl)}/api/auth/sign-out`,
157
+ { method: "POST", headers: { authorization: `Bearer ${accessToken}` } }
158
+ )
159
+ // 401: the session already ended, which is what signing out wanted.
160
+ if (!response.ok && response.status !== 401) throw await requestError(response, "sign out")
161
+ }
162
+ await options.store.clear()
163
+ }
164
+
165
+ /**
166
+ * A fetch that sends the stored session's access token to the API origin, refreshing it before it
167
+ * expires and once more when the API answers 401. Requests to other origins go out untouched.
168
+ */
169
+ export function createSixbSessionFetch(options: SixbSessionOptions): typeof fetch {
170
+ const base = options.fetch ?? globalThis.fetch
171
+ const apiOrigin = new URL(apiBase(options.baseUrl)).origin
172
+ const sessionFetch = async (
173
+ input: Parameters<typeof fetch>[0],
174
+ init?: Parameters<typeof fetch>[1]
175
+ ): Promise<Response> => {
176
+ const request = new Request(input, init)
177
+ if (new URL(request.url).origin !== apiOrigin) return base.call(globalThis, request)
178
+
179
+ const accessToken = await currentAccessToken(options)
180
+ if (!accessToken) return base.call(globalThis, request)
181
+ const retry = request.clone()
182
+ const response = await base.call(globalThis, withBearer(request, accessToken))
183
+ if (response.status !== 401) return response
184
+
185
+ // The access token was rejected before its expiry, so the session may have been refreshed or
186
+ // ended elsewhere. Retry once with whatever the store now holds, refreshing if nothing changed.
187
+ const stored = await options.store.load()
188
+ if (!stored) return response
189
+ let next: SixbSessionTokens
190
+ try {
191
+ next = stored.accessToken === accessToken ? await renewSession(options, stored) : stored
192
+ } catch (error) {
193
+ if (error instanceof SixbSessionEndedError) return response
194
+ throw error
195
+ }
196
+ return base.call(globalThis, withBearer(retry, next.accessToken))
197
+ }
198
+ return Object.assign(sessionFetch, { preconnect: base.preconnect })
199
+ }
200
+
201
+ async function currentAccessToken(options: SixbSessionOptions): Promise<string | null> {
202
+ try {
203
+ return await getSixbSessionAccessToken(options)
204
+ } catch (error) {
205
+ if (error instanceof SixbSessionEndedError) return null
206
+ throw error
207
+ }
208
+ }
209
+
210
+ function renewSession(
211
+ options: SixbSessionOptions,
212
+ stale: SixbSessionTokens
213
+ ): Promise<SixbSessionTokens> {
214
+ const pending = refreshing.get(options.store) ?? refreshStoredSession(options, stale)
215
+ refreshing.set(options.store, pending)
216
+ return pending
217
+ }
218
+
219
+ async function refreshStoredSession(
220
+ options: SixbSessionOptions,
221
+ stale: SixbSessionTokens
222
+ ): Promise<SixbSessionTokens> {
223
+ try {
224
+ // Another caller, or another process sharing the store, may have rotated the tokens since
225
+ // `stale` was read. Presenting a rotated refresh token later than the grace window would look
226
+ // like a stolen copy and revoke the session.
227
+ const latest = await options.store.load()
228
+ if (!latest) throw sessionEnded()
229
+ if (latest.refreshToken !== stale.refreshToken) return latest
230
+
231
+ const tokens = await refreshSixbSession({ ...options, refreshToken: latest.refreshToken })
232
+ await options.store.save(tokens)
233
+ return tokens
234
+ } catch (error) {
235
+ if (error instanceof SixbSessionEndedError) {
236
+ await options.store.clear()
237
+ options.onSessionEnded?.()
238
+ }
239
+ throw error
240
+ } finally {
241
+ refreshing.delete(options.store)
242
+ }
243
+ }
244
+
245
+ function sessionEnded(): SixbSessionEndedError {
246
+ return new SixbSessionEndedError("[SixbClient] The session has ended. Sign in again.")
247
+ }
248
+
249
+ function withBearer(request: Request, accessToken: string): Request {
250
+ const headers = new Headers(request.headers)
251
+ headers.set("authorization", `Bearer ${accessToken}`)
252
+ return new Request(request, { headers })
253
+ }
254
+
255
+ function sessionRequester(options: SixbSessionRequestOptions) {
256
+ const base = apiBase(options.baseUrl)
257
+ const request = options.fetch ?? globalThis.fetch
258
+ return (path: string, body: unknown, signal?: AbortSignal) =>
259
+ request(`${base}${path}`, {
260
+ method: "POST",
261
+ headers: { "content-type": "application/json" },
262
+ body: JSON.stringify(body),
263
+ signal,
264
+ })
265
+ }
266
+
267
+ function apiBase(baseUrl: string): string {
268
+ const normalized = normalizeSixbApiBaseUrl(baseUrl)
269
+ if (!/^https?:\/\//i.test(normalized)) {
270
+ throw new Error("[SixbClient] Session sign-in requires an absolute API base URL.")
271
+ }
272
+ return normalized
273
+ }
274
+
275
+ function parseSessionTokens(value: unknown): SixbSessionTokens {
276
+ const body = asRecord(value)
277
+ const accessToken = nonblank(body.accessToken)
278
+ const refreshToken = nonblank(body.refreshToken)
279
+ const expiresIn = body.expiresIn
280
+ if (!accessToken || !refreshToken || typeof expiresIn !== "number" || !(expiresIn > 0)) {
281
+ throw new Error("[SixbClient] The Sixb API returned invalid session tokens.")
282
+ }
283
+ return {
284
+ accessToken,
285
+ refreshToken,
286
+ accessExpiresAt: new Date(Date.now() + expiresIn * 1000).toISOString(),
287
+ }
288
+ }
289
+
290
+ async function requestError(response: Response, action: string): Promise<Error> {
291
+ const body = asRecord(await response.json().catch(() => null))
292
+ const detail = typeof body.error === "string" ? `: ${body.error}` : ""
293
+ return new Error(`[SixbClient] Could not ${action} (HTTP ${response.status})${detail}.`)
294
+ }
295
+
296
+ function sleep(ms: number, signal: AbortSignal | undefined): Promise<void> {
297
+ return new Promise((resolve, reject) => {
298
+ const timer = setTimeout(resolve, ms)
299
+ signal?.addEventListener(
300
+ "abort",
301
+ () => {
302
+ clearTimeout(timer)
303
+ reject(signal.reason)
304
+ },
305
+ { once: true }
306
+ )
307
+ })
308
+ }
309
+
310
+ function asRecord(value: unknown): Record<string, unknown> {
311
+ return typeof value === "object" && value !== null ? (value as Record<string, unknown>) : {}
312
+ }
313
+
314
+ function nonblank(value: unknown): string | undefined {
315
+ return typeof value === "string" && value.trim() ? value.trim() : undefined
316
+ }
@@ -1,11 +1,14 @@
1
1
  import { useEffect, useRef, useState } from "react"
2
2
  import { type AgentRunActivityEvent, createAgentActivitySocket } from "./agent-streams"
3
+ import type { Client } from "./generated/client"
3
4
  import type { ReconnectingSocketState } from "./ws-socket"
4
5
 
5
6
  export interface UseAgentActivityStreamOptions {
6
7
  readonly enabled?: boolean
7
8
  readonly reconnect?: boolean
8
9
  readonly reconnectDelayMs?: number
10
+ /** The client whose API and credential the socket uses. Defaults to the package's shared client. */
11
+ readonly client?: Client
9
12
  readonly onActivity?: (event: AgentRunActivityEvent) => void
10
13
  readonly onSubscribed?: () => void
11
14
  readonly onError?: (message: string) => void
@@ -19,7 +22,7 @@ const DISCONNECTED: ReconnectingSocketState = { connected: false, reconnecting:
19
22
  export function useAgentActivityStream(
20
23
  options: UseAgentActivityStreamOptions
21
24
  ): UseAgentActivityStreamResult {
22
- const { enabled = true, reconnect, reconnectDelayMs } = options
25
+ const { enabled = true, reconnect, reconnectDelayMs, client } = options
23
26
  const onActivityRef = useRef(options.onActivity)
24
27
  onActivityRef.current = options.onActivity
25
28
  const onSubscribedRef = useRef(options.onSubscribed)
@@ -36,13 +39,14 @@ export function useAgentActivityStream(
36
39
  const socket = createAgentActivitySocket({
37
40
  reconnect,
38
41
  reconnectDelayMs,
42
+ client,
39
43
  onActivity: (event) => onActivityRef.current?.(event),
40
44
  onSubscribed: () => onSubscribedRef.current?.(),
41
45
  onError: (message) => onErrorRef.current?.(message),
42
46
  onStateChange: setState,
43
47
  })
44
48
  return () => socket.close()
45
- }, [enabled, reconnect, reconnectDelayMs])
49
+ }, [enabled, reconnect, reconnectDelayMs, client])
46
50
 
47
51
  return state
48
52
  }
@@ -4,6 +4,7 @@ import {
4
4
  type AgentRunStreamEvent,
5
5
  createAgentRunSocket,
6
6
  } from "./agent-streams"
7
+ import type { Client } from "./generated/client"
7
8
  import type { ReconnectingSocketState } from "./ws-socket"
8
9
 
9
10
  export interface UseAgentRunStreamOptions {
@@ -12,6 +13,8 @@ export interface UseAgentRunStreamOptions {
12
13
  readonly enabled?: boolean
13
14
  readonly reconnect?: boolean
14
15
  readonly reconnectDelayMs?: number
16
+ /** The client whose API and credential the socket uses. Defaults to the package's shared client. */
17
+ readonly client?: Client
15
18
  readonly onEvent?: (event: AgentRunStreamEvent, cursor: string) => void
16
19
  readonly onRunSnapshot?: (run: AgentRunSnapshot) => void
17
20
  readonly onError?: (message: string) => void
@@ -25,10 +28,10 @@ const DISCONNECTED: ReconnectingSocketState = { connected: false, reconnecting:
25
28
  * React binding over {@link createAgentRunSocket}: opens the run's stream while enabled and mirrors
26
29
  * the transport's connection state into React state. Callbacks are read through refs so re-renders
27
30
  * with new callback identities never tear the socket down; the socket is re-created only when a
28
- * subscription-defining option (runId/afterCursor/enabled/reconnect) changes.
31
+ * subscription-defining option (runId/afterCursor/enabled/reconnect/client) changes.
29
32
  */
30
33
  export function useAgentRunStream(options: UseAgentRunStreamOptions): UseAgentRunStreamResult {
31
- const { runId, afterCursor, enabled = true, reconnect, reconnectDelayMs } = options
34
+ const { runId, afterCursor, enabled = true, reconnect, reconnectDelayMs, client } = options
32
35
  const onEventRef = useRef(options.onEvent)
33
36
  onEventRef.current = options.onEvent
34
37
  const onSnapshotRef = useRef(options.onRunSnapshot)
@@ -49,6 +52,7 @@ export function useAgentRunStream(options: UseAgentRunStreamOptions): UseAgentRu
49
52
  ...(afterCursor ? { afterCursor } : {}),
50
53
  reconnect,
51
54
  reconnectDelayMs,
55
+ client,
52
56
  onEvent: (event, cursor) => onEventRef.current?.(event, cursor),
53
57
  onRunSnapshot: (run) => onSnapshotRef.current?.(run),
54
58
  onError: (message) => onErrorRef.current?.(message),
@@ -56,7 +60,7 @@ export function useAgentRunStream(options: UseAgentRunStreamOptions): UseAgentRu
56
60
  })
57
61
 
58
62
  return () => socket.close()
59
- }, [enabled, runId, afterCursor, reconnect, reconnectDelayMs])
63
+ }, [enabled, runId, afterCursor, reconnect, reconnectDelayMs, client])
60
64
 
61
65
  return state
62
66
  }