@unieai/rabi-api-session-controller 0.0.0-stage → 0.2.2-rc.5

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 (137) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +7 -2
  3. package/lib/client.js +4 -0
  4. package/lib/index.js +4300 -0
  5. package/lib/typert.host.d.ts +3 -0
  6. package/lib/typert.host.js +5013 -0
  7. package/lib/typert.remote-client.d.ts +115 -0
  8. package/lib/typert.remote-client.js +2714 -0
  9. package/lib/types/agent.d.ts +164 -0
  10. package/lib/types/agent.js +484 -0
  11. package/lib/types/archived-session-gate.d.ts +33 -0
  12. package/lib/types/archived-session-gate.js +54 -0
  13. package/lib/types/assistant-stream.d.ts +26 -0
  14. package/lib/types/assistant-stream.js +82 -0
  15. package/lib/types/catalog.d.ts +24 -0
  16. package/lib/types/catalog.js +107 -0
  17. package/lib/types/client/contract/events.d.ts +102 -0
  18. package/lib/types/client/contract/events.js +111 -0
  19. package/lib/types/client/contract/session.d.ts +178 -0
  20. package/lib/types/client/contract/session.js +1 -0
  21. package/lib/types/client/contract/sessions.d.ts +162 -0
  22. package/lib/types/client/contract/sessions.js +1 -0
  23. package/lib/types/client/contract/snapshot.d.ts +84 -0
  24. package/lib/types/client/contract/snapshot.js +1 -0
  25. package/lib/types/client/index.d.ts +39 -0
  26. package/lib/types/client/index.js +60 -0
  27. package/lib/types/client/ordered-baseline.d.ts +12 -0
  28. package/lib/types/client/ordered-baseline.js +40 -0
  29. package/lib/types/client/scope.d.ts +46 -0
  30. package/lib/types/client/scope.js +46 -0
  31. package/lib/types/client/session-wire-event.d.ts +11 -0
  32. package/lib/types/client/session-wire-event.js +42 -0
  33. package/lib/types/client/sessions/assistant-stream.d.ts +56 -0
  34. package/lib/types/client/sessions/assistant-stream.js +182 -0
  35. package/lib/types/client/sessions/history-records.d.ts +22 -0
  36. package/lib/types/client/sessions/history-records.js +25 -0
  37. package/lib/types/client/sessions/lineage.d.ts +48 -0
  38. package/lib/types/client/sessions/lineage.js +55 -0
  39. package/lib/types/client/sessions/manager.d.ts +272 -0
  40. package/lib/types/client/sessions/manager.js +774 -0
  41. package/lib/types/client/sessions/notifier.d.ts +39 -0
  42. package/lib/types/client/sessions/notifier.js +97 -0
  43. package/lib/types/client/sessions/projection-store.d.ts +128 -0
  44. package/lib/types/client/sessions/projection-store.js +161 -0
  45. package/lib/types/client/sessions/remotes.d.ts +29 -0
  46. package/lib/types/client/sessions/remotes.js +7 -0
  47. package/lib/types/client/sessions/service.d.ts +263 -0
  48. package/lib/types/client/sessions/service.js +597 -0
  49. package/lib/types/client/sessions/session.d.ts +303 -0
  50. package/lib/types/client/sessions/session.js +991 -0
  51. package/lib/types/client/time-zone.d.ts +8 -0
  52. package/lib/types/client/time-zone.js +13 -0
  53. package/lib/types/client/transport.d.ts +77 -0
  54. package/lib/types/client/transport.js +130 -0
  55. package/lib/types/commands.d.ts +92 -0
  56. package/lib/types/commands.js +575 -0
  57. package/lib/types/continuation.d.ts +35 -0
  58. package/lib/types/continuation.js +47 -0
  59. package/lib/types/control.d.ts +20 -0
  60. package/lib/types/control.js +106 -0
  61. package/lib/types/file-references.d.ts +27 -0
  62. package/lib/types/file-references.js +68 -0
  63. package/lib/types/history/assistant-stream.d.ts +43 -0
  64. package/lib/types/history/assistant-stream.js +79 -0
  65. package/lib/types/history/controller.d.ts +104 -0
  66. package/lib/types/history/controller.js +293 -0
  67. package/lib/types/history/listener.d.ts +105 -0
  68. package/lib/types/history/listener.js +296 -0
  69. package/lib/types/history.d.ts +58 -0
  70. package/lib/types/history.js +152 -0
  71. package/lib/types/index.d.ts +262 -0
  72. package/lib/types/index.js +693 -0
  73. package/lib/types/list.d.ts +62 -0
  74. package/lib/types/list.js +343 -0
  75. package/lib/types/media-references.d.ts +18 -0
  76. package/lib/types/media-references.js +84 -0
  77. package/lib/types/remote-events.d.ts +8 -0
  78. package/lib/types/remote-events.js +1 -0
  79. package/lib/types/skill-catalog.d.ts +28 -0
  80. package/lib/types/skill-catalog.js +203 -0
  81. package/lib/types/state/controller.d.ts +45 -0
  82. package/lib/types/state/controller.js +288 -0
  83. package/lib/types/state/listener.d.ts +40 -0
  84. package/lib/types/state/listener.js +111 -0
  85. package/lib/types/types.d.ts +687 -0
  86. package/lib/types/types.js +5 -0
  87. package/lib/types/web/controller.d.ts +25 -0
  88. package/lib/types/web/controller.js +138 -0
  89. package/locale/de.json +6 -0
  90. package/locale/en.json +5 -0
  91. package/locale/es.json +6 -0
  92. package/locale/fr.json +6 -0
  93. package/locale/ja.json +6 -0
  94. package/locale/pt.json +6 -0
  95. package/locale/ru.json +6 -0
  96. package/locale/zh.json +6 -0
  97. package/package.json +119 -4
  98. package/src/agent.ts +474 -0
  99. package/src/archived-session-gate.ts +59 -0
  100. package/src/assistant-stream.ts +102 -0
  101. package/src/catalog.ts +117 -0
  102. package/src/client/contract/events.ts +205 -0
  103. package/src/client/contract/session.ts +174 -0
  104. package/src/client/contract/sessions.ts +169 -0
  105. package/src/client/contract/snapshot.ts +94 -0
  106. package/src/client/index.ts +149 -0
  107. package/src/client/ordered-baseline.ts +43 -0
  108. package/src/client/scope.ts +76 -0
  109. package/src/client/session-wire-event.ts +46 -0
  110. package/src/client/sessions/assistant-stream.ts +229 -0
  111. package/src/client/sessions/history-records.ts +35 -0
  112. package/src/client/sessions/lineage.ts +96 -0
  113. package/src/client/sessions/manager.ts +857 -0
  114. package/src/client/sessions/notifier.ts +97 -0
  115. package/src/client/sessions/projection-store.ts +244 -0
  116. package/src/client/sessions/remotes.ts +44 -0
  117. package/src/client/sessions/service.ts +741 -0
  118. package/src/client/sessions/session.ts +1055 -0
  119. package/src/client/time-zone.ts +14 -0
  120. package/src/client/transport.ts +247 -0
  121. package/src/commands.ts +602 -0
  122. package/src/continuation.ts +58 -0
  123. package/src/control.ts +121 -0
  124. package/src/file-references.ts +42 -0
  125. package/src/history/assistant-stream.ts +102 -0
  126. package/src/history/controller.ts +256 -0
  127. package/src/history/listener.ts +302 -0
  128. package/src/history.ts +189 -0
  129. package/src/index.ts +651 -0
  130. package/src/list.ts +382 -0
  131. package/src/media-references.ts +84 -0
  132. package/src/remote-events.ts +14 -0
  133. package/src/skill-catalog.ts +108 -0
  134. package/src/state/controller.ts +221 -0
  135. package/src/state/listener.ts +116 -0
  136. package/src/types.ts +720 -0
  137. package/src/web/controller.ts +78 -0
@@ -0,0 +1,203 @@
1
+ /** Session-addressed, cold-readable skill catalog Remote. */
2
+ var __runInitializers = (this && this.__runInitializers) || function (thisArg, initializers, value) {
3
+ var useValue = arguments.length > 2;
4
+ for (var i = 0; i < initializers.length; i++) {
5
+ value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
6
+ }
7
+ return useValue ? value : void 0;
8
+ };
9
+ var __esDecorate = (this && this.__esDecorate) || function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
10
+ function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; }
11
+ var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
12
+ var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
13
+ var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
14
+ var _, done = false;
15
+ for (var i = decorators.length - 1; i >= 0; i--) {
16
+ var context = {};
17
+ for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
18
+ for (var p in contextIn.access) context.access[p] = contextIn.access[p];
19
+ context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); };
20
+ var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
21
+ if (kind === "accessor") {
22
+ if (result === void 0) continue;
23
+ if (result === null || typeof result !== "object") throw new TypeError("Object expected");
24
+ if (_ = accept(result.get)) descriptor.get = _;
25
+ if (_ = accept(result.set)) descriptor.set = _;
26
+ if (_ = accept(result.init)) initializers.unshift(_);
27
+ }
28
+ else if (_ = accept(result)) {
29
+ if (kind === "field") initializers.unshift(_);
30
+ else descriptor[key] = _;
31
+ }
32
+ }
33
+ if (target) Object.defineProperty(target, contextIn.name, descriptor);
34
+ done = true;
35
+ };
36
+ var __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) {
37
+ if (value !== null && value !== void 0) {
38
+ if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
39
+ var dispose, inner;
40
+ if (async) {
41
+ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
42
+ dispose = value[Symbol.asyncDispose];
43
+ }
44
+ if (dispose === void 0) {
45
+ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
46
+ dispose = value[Symbol.dispose];
47
+ if (async) inner = dispose;
48
+ }
49
+ if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
50
+ if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };
51
+ env.stack.push({ value: value, dispose: dispose, async: async });
52
+ }
53
+ else if (async) {
54
+ env.stack.push({ async: true });
55
+ }
56
+ return value;
57
+ };
58
+ var __disposeResources = (this && this.__disposeResources) || (function (SuppressedError) {
59
+ return function (env) {
60
+ function fail(e) {
61
+ env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
62
+ env.hasError = true;
63
+ }
64
+ var r, s = 0;
65
+ function next() {
66
+ while (r = env.stack.pop()) {
67
+ try {
68
+ if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
69
+ if (r.dispose) {
70
+ var result = r.dispose.call(r.value);
71
+ if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });
72
+ }
73
+ else s |= 1;
74
+ }
75
+ catch (e) {
76
+ fail(e);
77
+ }
78
+ }
79
+ if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
80
+ if (env.hasError) throw env.error;
81
+ }
82
+ return next();
83
+ };
84
+ })(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
85
+ var e = new Error(message);
86
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
87
+ });
88
+ import { SessionQueryError } from '@unieai/rabi-session-query';
89
+ import { isUserInvocable } from '@unieai/rabi-skill';
90
+ import { Remote, RemoteError, TypertRemoteService } from '@unieai/rabi-typert-protocol';
91
+ /** Host service backing `ctx.remote.skills` without activating a cold Agent. */
92
+ let SessionSkillCatalog = (() => {
93
+ let _classSuper = TypertRemoteService;
94
+ let _instanceExtraInitializers = [];
95
+ let _list_decorators;
96
+ return class SessionSkillCatalog extends _classSuper {
97
+ static {
98
+ const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
99
+ _list_decorators = [Remote];
100
+ __esDecorate(this, null, _list_decorators, { kind: "method", name: "list", static: false, private: false, access: { has: obj => "list" in obj, get: obj => obj.list }, metadata: _metadata }, null, _instanceExtraInitializers);
101
+ if (_metadata) Object.defineProperty(this, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
102
+ }
103
+ static inject = ['agents', 'sessionQuery', 'typert', 'workingDirectory'];
104
+ /** @param ctx - Host context carrying Session reads and optional skill/preset services. */
105
+ constructor(ctx) {
106
+ super(ctx, 'sessionSkillCatalog', { namespace: 'skills' });
107
+ __runInitializers(this, _instanceExtraInitializers);
108
+ }
109
+ /**
110
+ * List the user-invocable skills visible to one Session composition.
111
+ * @param request - Session identity whose cwd and preset select the catalog view.
112
+ * @param signal - caller lifetime carried by the Remote transport; admitted catalog reads retain their existing completion semantics.
113
+ * @returns user-invocable skill metadata without loading skill bodies.
114
+ * @throws RemoteError when the Session cannot be inspected or no registry can serve it.
115
+ */
116
+ async list(request, signal) {
117
+ const env_1 = { stack: [], error: void 0, hasError: false };
118
+ try {
119
+ const { sessionId } = request;
120
+ let cwd;
121
+ let agentPreset;
122
+ try {
123
+ const env_2 = { stack: [], error: void 0, hasError: false };
124
+ try {
125
+ const observation = __addDisposableResource(env_2, await this.ctx.sessionQuery.observeSession(sessionId), false);
126
+ if (observation.projections === undefined) {
127
+ throw new Error('skill catalog requires a projected Session observation');
128
+ }
129
+ cwd = observation.projections.values.workingDirectory
130
+ ?? observation.header.cwd
131
+ ?? this.ctx.workingDirectory.defaultDirectory;
132
+ agentPreset = observation.projections.values.agentPreset ?? undefined;
133
+ const live = this.ctx.agents.get(sessionId);
134
+ if (live !== undefined)
135
+ cwd = await this.ctx.workingDirectory.ensure(live, signal);
136
+ }
137
+ catch (e_1) {
138
+ env_2.error = e_1;
139
+ env_2.hasError = true;
140
+ }
141
+ finally {
142
+ __disposeResources(env_2);
143
+ }
144
+ }
145
+ catch (error) {
146
+ if (error instanceof SessionQueryError
147
+ && error.code === 'SESSION_QUERY_SESSION_NOT_FOUND') {
148
+ throw new RemoteError('session/not-found', `session "${sessionId}" not found`, { sessionId });
149
+ }
150
+ throw new RemoteError('gateway/internal', `session "${sessionId}" could not be inspected: ${String(error)}`, {});
151
+ }
152
+ const live = this.ctx.agents.get(sessionId);
153
+ const presets = this.ctx.get('agentPresets');
154
+ const scoped = live === undefined ? undefined : presets?.serviceFor(live, 'skills');
155
+ const skillRegistry = scoped ?? this.ctx.get('skills');
156
+ if (skillRegistry === undefined) {
157
+ throw new RemoteError('gateway/internal', 'skill registry is absent: neither this session\'s agent preset nor the host composition mounts @unieai/rabi-skill', {});
158
+ }
159
+ const lease = __addDisposableResource(env_1, live === undefined ? await this.scopeFor(agentPreset) : undefined, true);
160
+ const scope = live ?? lease?.key;
161
+ try {
162
+ const skills = (await skillRegistry.list({ cwd, scope })).filter(isUserInvocable);
163
+ return {
164
+ skills: skills.map(skill => ({
165
+ name: skill.name,
166
+ ...skill.path === undefined ? {} : { path: skill.path },
167
+ description: skill.description,
168
+ ...skill.whenToUse === undefined ? {} : { whenToUse: skill.whenToUse },
169
+ modelInvocable: skill.invocation.modelInvocable,
170
+ })),
171
+ };
172
+ }
173
+ catch (error) {
174
+ throw new RemoteError('gateway/internal', `skill listing failed: ${String(error)}`, {});
175
+ }
176
+ }
177
+ catch (e_2) {
178
+ env_1.error = e_2;
179
+ env_1.hasError = true;
180
+ }
181
+ finally {
182
+ const result_1 = __disposeResources(env_1);
183
+ if (result_1)
184
+ await result_1;
185
+ }
186
+ }
187
+ /** Resolve a live or standing preset scope without creating an Agent. */
188
+ async scopeFor(agentPreset) {
189
+ const presets = this.ctx.get('agentPresets');
190
+ if (presets === undefined)
191
+ return undefined;
192
+ try {
193
+ return await presets.acquireScope(agentPreset);
194
+ }
195
+ catch {
196
+ // An unknown or unusable recorded preset falls back to the global registry.
197
+ return undefined;
198
+ }
199
+ }
200
+ };
201
+ })();
202
+ export { SessionSkillCatalog };
203
+ export default SessionSkillCatalog;
@@ -0,0 +1,45 @@
1
+ /** Passive Session state, coalesced observations and quiescence waits. */
2
+ import type { Context } from '@unieai/cordis';
3
+ import type { HistoryController } from '../history/controller.ts';
4
+ import type { SessionState, SessionStateRequest, SessionWaitRequest, SessionWaitValue } from '../types.ts';
5
+ /** Reads and waits without activating or cancelling Session execution. */
6
+ export declare class StateController {
7
+ private readonly ctx;
8
+ private readonly historyController;
9
+ /**
10
+ * @param ctx - live Session and pending Remote event services.
11
+ * @param historyController - passive read entry used for cold state and its bounded output.
12
+ */
13
+ constructor(ctx: Context, historyController: HistoryController);
14
+ /**
15
+ * Read passive execution and pending-input state.
16
+ * @param request - Session identity.
17
+ * @param signal - read cancellation.
18
+ * @returns current passive state.
19
+ */
20
+ state(request: SessionStateRequest, signal: AbortSignal): Promise<SessionState>;
21
+ /**
22
+ * Observe complete passive state replacements.
23
+ * @param request - Session identity.
24
+ * @param signal - observation cancellation.
25
+ * @returns complete state replacements, starting with the current state.
26
+ */
27
+ observeState(request: SessionStateRequest, signal: AbortSignal): AsyncIterable<SessionState>;
28
+ /**
29
+ * Wait for quiescence, pending input, or the deadline without cancelling execution.
30
+ * @param request - Session identity, timeout and assistant output window.
31
+ * @param signal - cancellation of this wait only, never of Agent execution.
32
+ * @returns the stopping reason and last complete state; no state before timeout is an error.
33
+ */
34
+ wait(request: SessionWaitRequest, signal: AbortSignal): Promise<SessionWaitValue>;
35
+ private listen;
36
+ /**
37
+ * @param sessionId - Session to sample.
38
+ * @param signal - read cancellation.
39
+ * @param retried - whether a live source already redirected this read once.
40
+ * @returns one passive state sample.
41
+ */
42
+ private readState;
43
+ private pendingInput;
44
+ }
45
+ //# sourceMappingURL=controller.d.ts.map
@@ -0,0 +1,288 @@
1
+ /** Passive Session state, coalesced observations and quiescence waits. */
2
+ var __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) {
3
+ if (value !== null && value !== void 0) {
4
+ if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
5
+ var dispose, inner;
6
+ if (async) {
7
+ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
8
+ dispose = value[Symbol.asyncDispose];
9
+ }
10
+ if (dispose === void 0) {
11
+ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
12
+ dispose = value[Symbol.dispose];
13
+ if (async) inner = dispose;
14
+ }
15
+ if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
16
+ if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };
17
+ env.stack.push({ value: value, dispose: dispose, async: async });
18
+ }
19
+ else if (async) {
20
+ env.stack.push({ async: true });
21
+ }
22
+ return value;
23
+ };
24
+ var __disposeResources = (this && this.__disposeResources) || (function (SuppressedError) {
25
+ return function (env) {
26
+ function fail(e) {
27
+ env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
28
+ env.hasError = true;
29
+ }
30
+ var r, s = 0;
31
+ function next() {
32
+ while (r = env.stack.pop()) {
33
+ try {
34
+ if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
35
+ if (r.dispose) {
36
+ var result = r.dispose.call(r.value);
37
+ if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });
38
+ }
39
+ else s |= 1;
40
+ }
41
+ catch (e) {
42
+ fail(e);
43
+ }
44
+ }
45
+ if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
46
+ if (env.hasError) throw env.error;
47
+ }
48
+ return next();
49
+ };
50
+ })(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
51
+ var e = new Error(message);
52
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
53
+ });
54
+ import { deadline, MAX_TIMER_DELAY_MS, timeoutOf } from '@unieai/rabi-timeout';
55
+ import { RemoteError } from '@unieai/rabi-typert-protocol';
56
+ import { DEFAULT_MAX_MESSAGES, rejectNotFound } from "../history.js";
57
+ import { StateListener } from "./listener.js";
58
+ const DEFAULT_WAIT_TIMEOUT_MS = 30_000;
59
+ /** Reads and waits without activating or cancelling Session execution. */
60
+ export class StateController {
61
+ ctx;
62
+ historyController;
63
+ /**
64
+ * @param ctx - live Session and pending Remote event services.
65
+ * @param historyController - passive read entry used for cold state and its bounded output.
66
+ */
67
+ constructor(ctx, historyController) {
68
+ this.ctx = ctx;
69
+ this.historyController = historyController;
70
+ }
71
+ /**
72
+ * Read passive execution and pending-input state.
73
+ * @param request - Session identity.
74
+ * @param signal - read cancellation.
75
+ * @returns current passive state.
76
+ */
77
+ async state(request, signal) {
78
+ return this.readState(request.sessionId, signal);
79
+ }
80
+ /**
81
+ * Observe complete passive state replacements.
82
+ * @param request - Session identity.
83
+ * @param signal - observation cancellation.
84
+ * @returns complete state replacements, starting with the current state.
85
+ */
86
+ async *observeState(request, signal) {
87
+ const env_1 = { stack: [], error: void 0, hasError: false };
88
+ try {
89
+ const listener = __addDisposableResource(env_1, this.listen(request.sessionId, signal), false);
90
+ for await (const { state } of listener.observeStates())
91
+ yield state;
92
+ }
93
+ catch (e_1) {
94
+ env_1.error = e_1;
95
+ env_1.hasError = true;
96
+ }
97
+ finally {
98
+ __disposeResources(env_1);
99
+ }
100
+ }
101
+ /**
102
+ * Wait for quiescence, pending input, or the deadline without cancelling execution.
103
+ * @param request - Session identity, timeout and assistant output window.
104
+ * @param signal - cancellation of this wait only, never of Agent execution.
105
+ * @returns the stopping reason and last complete state; no state before timeout is an error.
106
+ */
107
+ async wait(request, signal) {
108
+ const env_2 = { stack: [], error: void 0, hasError: false };
109
+ try {
110
+ const timeoutMs = request.timeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS;
111
+ const afterSeq = request.afterSeq ?? -1;
112
+ const maxMessages = request.maxMessages ?? DEFAULT_MAX_MESSAGES;
113
+ if (!Number.isSafeInteger(afterSeq) || afterSeq < -1 || Object.is(afterSeq, -0)) {
114
+ throw new RemoteError('gateway/bad-request', 'afterSeq must be an integer greater than or equal to -1', {});
115
+ }
116
+ if (!Number.isSafeInteger(maxMessages) || maxMessages <= 0) {
117
+ throw new RemoteError('gateway/bad-request', 'maxMessages must be a positive safe integer', {});
118
+ }
119
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0 || timeoutMs > MAX_TIMER_DELAY_MS) {
120
+ throw new RemoteError('gateway/bad-request', 'timeoutMs must be a positive supported timer delay', {});
121
+ }
122
+ const timer = __addDisposableResource(env_2, deadline(signal, timeoutMs, 'session/wait-timeout'), false);
123
+ const listener = __addDisposableResource(env_2, this.listen(request.sessionId, timer.signal), false);
124
+ const sessionId = request.sessionId;
125
+ const statesGenerator = listener.observeStates(1_000);
126
+ let nextStatePromise = statesGenerator.next();
127
+ let currentState;
128
+ let reason = 'timeout';
129
+ try {
130
+ for (;;) {
131
+ const observedState = await nextStatePromise;
132
+ if (observedState.done) {
133
+ timer.signal.throwIfAborted();
134
+ throw new RemoteError('session/observation-ended', 'Session observation ended before a stopping state', {});
135
+ }
136
+ nextStatePromise = statesGenerator.next();
137
+ // Observe rejection on immediate exits without replacing the original demand.
138
+ void nextStatePromise.catch(() => undefined);
139
+ // Only a state the listener still confirms may drive this wait; an invalidated
140
+ // sample never becomes the state a timeout reports.
141
+ if (!listener.isCurrent(observedState.value.revision))
142
+ continue;
143
+ currentState = observedState.value.state;
144
+ const action = computeWaitAction(currentState);
145
+ if (action === 'continue')
146
+ continue;
147
+ if (action === 'input-required' || action === 'idle') {
148
+ reason = action;
149
+ break;
150
+ }
151
+ const agent = this.ctx.agents.get(sessionId);
152
+ if (agent === undefined || this.ctx.sessions.get(sessionId) !== agent.session)
153
+ continue;
154
+ if (await waitForIdleOrStateChange(agent, nextStatePromise) === 'state-changed')
155
+ continue;
156
+ if (!listener.isCurrent(observedState.value.revision) || this.ctx.agents.get(sessionId) !== agent
157
+ || this.ctx.sessions.get(sessionId) !== agent.session)
158
+ continue;
159
+ reason = 'idle';
160
+ break;
161
+ }
162
+ }
163
+ catch (error) {
164
+ // A caller cancellation is never a wait outcome; the deadline absorbs only the read
165
+ // it cancelled, and any other failure keeps its own error.
166
+ if (signal.aborted)
167
+ throw signal.reason;
168
+ if (!expired(timer.signal, error))
169
+ throw error;
170
+ }
171
+ finally {
172
+ // Wake/cancel a pending read before asking the generator to return.
173
+ listener[Symbol.dispose]();
174
+ await nextStatePromise.catch(() => undefined);
175
+ await statesGenerator.return(undefined);
176
+ }
177
+ signal.throwIfAborted();
178
+ if (currentState === undefined)
179
+ throw new RemoteError('session/wait-timeout', 'No Session state arrived before the wait deadline', {});
180
+ const output = await this.historyController.assistantOutput(sessionId, afterSeq, currentState.cursor, maxMessages, signal);
181
+ return { reason, state: currentState, output };
182
+ }
183
+ catch (e_2) {
184
+ env_2.error = e_2;
185
+ env_2.hasError = true;
186
+ }
187
+ finally {
188
+ __disposeResources(env_2);
189
+ }
190
+ }
191
+ listen(sessionId, signal) {
192
+ return new StateListener(this.ctx, sessionId, signal, readSignal => this.readState(sessionId, readSignal));
193
+ }
194
+ /**
195
+ * @param sessionId - Session to sample.
196
+ * @param signal - read cancellation.
197
+ * @param retried - whether a live source already redirected this read once.
198
+ * @returns one passive state sample.
199
+ */
200
+ async readState(sessionId, signal, retried = false) {
201
+ signal.throwIfAborted();
202
+ const agent = this.ctx.agents.get(sessionId);
203
+ if (agent !== undefined) {
204
+ if (agent.session.header.cwd === undefined)
205
+ rejectNotFound({ kind: 'session', sessionId });
206
+ return {
207
+ cursor: agent.session.seq - 1,
208
+ active: true,
209
+ running: agent.status === 'running',
210
+ queue: queueItems(agent),
211
+ pendingInput: this.pendingInput(agent.session.id),
212
+ };
213
+ }
214
+ const state = await this.historyController.usingObservation({ sessionId, projection: false }, signal, (observation) => {
215
+ // A live source means the Session attached during this read; report its live state
216
+ // rather than a live cursor paired with an inactive sample.
217
+ if (!retried && observation.source === 'live')
218
+ return undefined;
219
+ if (observation.header.cwd === undefined)
220
+ rejectNotFound({ kind: 'session', sessionId });
221
+ return {
222
+ cursor: observation.cursor,
223
+ active: false,
224
+ running: false,
225
+ queue: null,
226
+ pendingInput: this.pendingInput(observation.header.id),
227
+ };
228
+ });
229
+ signal.throwIfAborted();
230
+ return state ?? this.readState(sessionId, signal, true);
231
+ }
232
+ pendingInput(sessionId) {
233
+ const kinds = new Set();
234
+ for (const { event, agentId } of this.ctx.typertGateway.getPendingRemoteEvents()) {
235
+ if (String(agentId) !== sessionId)
236
+ continue;
237
+ kinds.add(event === 'approval/request' ? 'approval' : event === 'user-questions/request' ? 'question' : 'other');
238
+ }
239
+ return [...kinds];
240
+ }
241
+ }
242
+ /**
243
+ * @param signal - wait deadline signal.
244
+ * @param error - failure raised by the in-flight read.
245
+ * @returns whether the deadline expired and cancelled that read.
246
+ */
247
+ function expired(signal, error) {
248
+ const reason = timeoutOf(signal, 'session/wait-timeout');
249
+ if (reason === undefined)
250
+ return false;
251
+ // Cancellation carries the deadline reason along its cause chain; any other failure does not.
252
+ let current = error;
253
+ for (let depth = 0; depth < 4 && current instanceof Error; depth++) {
254
+ if (current === reason || current.cause === reason)
255
+ return true;
256
+ current = current.cause;
257
+ }
258
+ return error === reason;
259
+ }
260
+ /** Choose the next wait action; check-idle requires the caller's whenIdle and identity checks. */
261
+ function computeWaitAction(state) {
262
+ if (state.pendingInput.length > 0)
263
+ return 'input-required';
264
+ if (state.running)
265
+ return 'continue';
266
+ if (!state.active)
267
+ return 'idle';
268
+ return 'check-idle';
269
+ }
270
+ /** Wait for either driver quiescence or the already-armed next state; preserve rejections from both. */
271
+ function waitForIdleOrStateChange(agent, nextStatePromise) {
272
+ return Promise.race([
273
+ agent.whenIdle().then(() => 'idle'),
274
+ nextStatePromise.then(() => 'state-changed'),
275
+ ]);
276
+ }
277
+ function queueItems(agent) {
278
+ const item = (message, placement) => ({
279
+ id: message.id,
280
+ placement,
281
+ ...message.source.kind === 'user' && 'rpcId' in message.source ? { rpcId: message.source.rpcId } : {},
282
+ content: message.content,
283
+ });
284
+ return [
285
+ ...agent.inbox.nextTurn.map(message => item(message, 'queued')),
286
+ ...agent.inbox.nextStep.map(message => item(message, message.source.kind === 'user' ? 'steering' : 'context')),
287
+ ];
288
+ }
@@ -0,0 +1,40 @@
1
+ /** Coalesced Session state observations with Host-local revisions. */
2
+ import type { Context } from '@unieai/cordis';
3
+ import type { SessionId } from '@unieai/rabi-session';
4
+ import type { SessionState } from '../types.ts';
5
+ /** One complete state with its listener-local revision. */
6
+ export interface VersionedSessionState {
7
+ state: SessionState;
8
+ revision: number;
9
+ }
10
+ /** Coalesces Session/Agent invalidations with local revisions; pending events are sampled on reads. */
11
+ export declare class StateListener implements Disposable {
12
+ private readonly readState;
13
+ private readonly disposes;
14
+ private readonly cancellation;
15
+ private readonly signal;
16
+ private revision;
17
+ private resolver;
18
+ private closed;
19
+ /**
20
+ * @param ctx - lifecycle notification owner.
21
+ * @param target - Session to observe.
22
+ * @param signal - caller cancellation.
23
+ * @param readState - passive complete-state reader.
24
+ */
25
+ constructor(ctx: Context, target: SessionId, signal: AbortSignal, readState: (signal: AbortSignal) => Promise<SessionState>);
26
+ /**
27
+ * Check whether a completed read still represents the latest invalidation.
28
+ * @param revision - revision captured with a completed read.
29
+ * @returns whether no intervening invalidation occurred.
30
+ */
31
+ isCurrent(revision: number): boolean;
32
+ /**
33
+ * Read coalesced state replacements with optional periodic refresh.
34
+ * @param refreshMs - optional idle recheck interval; omitted for event-only observation.
35
+ * @returns complete state replacements with internal consistency revisions.
36
+ */
37
+ observeStates(refreshMs?: number): AsyncGenerator<VersionedSessionState>;
38
+ [Symbol.dispose](): void;
39
+ }
40
+ //# sourceMappingURL=listener.d.ts.map