@celljs/ta-quick-talk 0.0.0-stage → 4.44.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/README.en.md ADDED
@@ -0,0 +1,9 @@
1
+ # Cell - Ta Quick Talk
2
+
3
+ Talking in place for pages of play that have the user's Ta in them (a plain library, not a pi package): in the town (`ta-town`) and Block Earth (`ta-earth`), a line said to the double, an agent or a channel without leaving the world (typed or held to talk); the page shows the talk as a short thread, the answer in full once it is written, read aloud when the user talked by voice.
4
+
5
+ - `useQuickTalk(pi, options)`: a React hook keeping what was said, the wait, the answer and the reading; the double through its page's `send`, an agent through its own session (opened by ta-channels when it is not), a channel by a post of ta-channels.
6
+ - `QuickTalkUtil`: where a talk is (`next`), whom the user talks with (`talking`), the last lines (`thread`).
7
+ - `askChannels` / `agentSession`: the methods of the host of ta-channels, by `pi.packages.callPackageHost`; with ta-channels off the call fails and the page goes on.
8
+
9
+ It was in ta-channels (moved there from ta-town on 2026-11-29 to be shared). pi packages bundle no module of one another (AGENTS.md "pi first"), so on 2026-11-30 it became this library, ta-channels giving agents and channels by calls alone.
package/README.md CHANGED
@@ -1,3 +1,9 @@
1
- # Temporary Holding Version
1
+ # Cell - Ta Quick Talk
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ 给有用户自己的 Ta 的游戏页面用的就地对话(普通的库,不是 pi 包):在小镇(`ta-town`)、方块地球(`ta-earth`)里不离开世界,对分身、某个智能体或频道说一句话(打字或按住说话),页面把这一来一回显示成一小段对话,回答写完后给出全文,按住说话时把回答念出来。
4
+
5
+ - `useQuickTalk(pi, options)`:React hook,管说出的话、等待、回答和朗读;分身经它页面的 `send`,智能体经它自己的会话(没开就由 ta-channels 打开),频道经 ta-channels 发帖。
6
+ - `QuickTalkUtil`:一次对话进行到哪了(`next`)、和谁在说(`talking`)、最近几句(`thread`)。
7
+ - `askChannels` / `agentSession`:经 `pi.packages.callPackageHost` 调 ta-channels 的宿主方法,ta-channels 关着时调用失败、页面照常。
8
+
9
+ 它原在 ta-channels 里(2026-11-29 从 ta-town 挪过去共用)。pi 包之间不打包彼此的模块(AGENTS.md "pi first"),所以 2026-11-30 拆成这个库,ta-channels 只经调用提供智能体和频道。
package/esm/index.d.ts ADDED
@@ -0,0 +1 @@
1
+ export * from './quick-talk.js';
package/esm/index.js ADDED
@@ -0,0 +1,2 @@
1
+ export * from './quick-talk.js';
2
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,3 @@
1
+ {
2
+ "type": "module"
3
+ }
@@ -0,0 +1,93 @@
1
+ import type { TaSessionInfo } from '@celljs/ta-protocol';
2
+ import type { WebExtensionAPI, WebViewInfo } from '@celljs/ta-web/lib/browser/extension/web-extension-api';
3
+ /** The double's page. */
4
+ export declare const DOUBLE_PAGE = "assistant/assistant";
5
+ export type QuickTalkPhase = 'sending' | 'waiting' | 'answering' | 'done' | 'failed';
6
+ export interface QuickTalk {
7
+ /** A resident's id, or a meeting room's place id. */
8
+ to: string;
9
+ kind: 'double' | 'agent' | 'room';
10
+ said: string;
11
+ /** Said by voice: the answer is read aloud. */
12
+ voice: boolean;
13
+ sentAt: number;
14
+ phase: QuickTalkPhase;
15
+ sessionId?: string;
16
+ /** The last line of the one talked to as the user spoke: an answer is a line after it. */
17
+ baseline?: {
18
+ text: string;
19
+ at: number;
20
+ };
21
+ reply?: string;
22
+ error?: string;
23
+ }
24
+ /** An agent as a page knows it: its session file, when it has one open. */
25
+ export interface QuickTalkAgent {
26
+ id: string;
27
+ sessionFile?: string;
28
+ }
29
+ export interface QuickTalkTarget {
30
+ to: string;
31
+ kind: QuickTalk['kind'];
32
+ agent?: QuickTalkAgent;
33
+ channelId?: string;
34
+ }
35
+ export interface QuickTalkOptions {
36
+ /** The agents of the user's team, as the page has them. */
37
+ agents: readonly QuickTalkAgent[];
38
+ sessions: readonly TaSessionInfo[];
39
+ /** The double's page (`ui.useView(DOUBLE_PAGE)`). */
40
+ double: WebViewInfo | undefined;
41
+ /** What is said when the Ta service is too old to open an agent's session. */
42
+ oldService: string;
43
+ /** Marks the messages sent (`clientMessageId`), by the page: `town`, `earth`. */
44
+ tag: string;
45
+ }
46
+ /** A request to ta-channels' host. */
47
+ export declare function askChannels(pi: WebExtensionAPI, request: Record<string, unknown>): Promise<unknown>;
48
+ /**
49
+ * The session of an agent, opened by ta-channels if it is not. A Ta service started before its pages called it
50
+ * (14 Nov 2026) answers nothing: the user is told `oldService` rather than shown a TypeError.
51
+ */
52
+ export declare function agentSession(pi: WebExtensionAPI, agentId: string, oldService: string): Promise<string>;
53
+ export declare namespace QuickTalkUtil {
54
+ /**
55
+ * Whom a talk is with, as the model shows it: standing and listening while the user talks to it or waits,
56
+ * then answering. `listening`: whom the user holds the box to talk to now.
57
+ */
58
+ function talking(talk: QuickTalk | undefined, listening?: string): {
59
+ id: string;
60
+ answering: boolean;
61
+ } | undefined;
62
+ /** The talks with one, the last `count` of them, oldest first. */
63
+ function thread(talks: readonly QuickTalk[], to: string, count?: number): QuickTalk[];
64
+ /** Whether one is still answering: the send button stops it then. */
65
+ function working(talk: QuickTalk | undefined): boolean;
66
+ /**
67
+ * Where a talk is now, by what the double's page or the agent's session says: it answers once seen at work,
68
+ * and has answered once it stops with a last line that is not what the user said, nor the line it had as
69
+ * the user spoke (`baseline`; without one, a line later than the talk, by the clock).
70
+ */
71
+ function next(talk: QuickTalk, now: {
72
+ busy: boolean;
73
+ line?: {
74
+ text: string;
75
+ at: number;
76
+ };
77
+ }, at?: number): Pick<QuickTalk, 'phase' | 'reply'> | undefined;
78
+ }
79
+ export declare function useQuickTalk(pi: WebExtensionAPI, { agents, sessions, double, oldService, tag }: QuickTalkOptions): {
80
+ talk: QuickTalk;
81
+ talks: QuickTalk[];
82
+ speaking: boolean;
83
+ listening: string | undefined;
84
+ send: (target: QuickTalkTarget, text: string, byVoice: boolean) => void;
85
+ spoken: () => void;
86
+ stop: () => void;
87
+ speak: (text: string) => void;
88
+ hush: () => void;
89
+ /** Whom the user holds the box to talk to, or none. */
90
+ listen: import("react").Dispatch<import("react").SetStateAction<string | undefined>>;
91
+ clear: () => void;
92
+ };
93
+ export type QuickTalkState = ReturnType<typeof useQuickTalk>;
@@ -0,0 +1,223 @@
1
+ // Talking to the double or an agent from a page of play without leaving it (useQuickTalk; the town, Block Earth): what
2
+ // the user says (typed, or held to talk) goes to the double (its page's `send`), to an agent's own session, or into a
3
+ // channel; the page shows the talk as a short thread, the answer in full once it is written, and reads it aloud when
4
+ // the user talked by voice. One for every page that has the user's Ta in it, so that they all talk the same way.
5
+ const CHANNELS = '@celljs/ta-channels';
6
+ /** The double's page. */
7
+ export const DOUBLE_PAGE = 'assistant/assistant';
8
+ /** Past that, an answer that never came is no longer waited for. */
9
+ const WAIT_MS = 5 * 60000;
10
+ /** Talks kept, of all the residents. */
11
+ const KEPT = 24;
12
+ /** A request to ta-channels' host. */
13
+ export function askChannels(pi, request) {
14
+ return pi.packages.callPackageHost(CHANNELS, 'request', [request]);
15
+ }
16
+ /**
17
+ * The session of an agent, opened by ta-channels if it is not. A Ta service started before its pages called it
18
+ * (14 Nov 2026) answers nothing: the user is told `oldService` rather than shown a TypeError.
19
+ */
20
+ export async function agentSession(pi, agentId, oldService) {
21
+ const answer = (await askChannels(pi, { kind: 'openAgent', agent: agentId }));
22
+ if (typeof (answer === null || answer === void 0 ? void 0 : answer.sessionId) !== 'string' || !answer.sessionId) {
23
+ throw new Error(oldService);
24
+ }
25
+ return answer.sessionId;
26
+ }
27
+ export var QuickTalkUtil;
28
+ (function (QuickTalkUtil) {
29
+ /**
30
+ * Whom a talk is with, as the model shows it: standing and listening while the user talks to it or waits,
31
+ * then answering. `listening`: whom the user holds the box to talk to now.
32
+ */
33
+ function talking(talk, listening) {
34
+ if (listening && !listening.startsWith('room:')) {
35
+ return { id: listening, answering: false };
36
+ }
37
+ if (!talk || talk.kind === 'room' || talk.phase === 'done' || talk.phase === 'failed') {
38
+ return undefined;
39
+ }
40
+ return { id: talk.to, answering: talk.phase === 'answering' };
41
+ }
42
+ QuickTalkUtil.talking = talking;
43
+ /** The talks with one, the last `count` of them, oldest first. */
44
+ function thread(talks, to, count = 6) {
45
+ return talks.filter(talk => talk.to === to).slice(-count);
46
+ }
47
+ QuickTalkUtil.thread = thread;
48
+ /** Whether one is still answering: the send button stops it then. */
49
+ function working(talk) {
50
+ return !!talk && (talk.phase === 'sending' || talk.phase === 'waiting' || talk.phase === 'answering');
51
+ }
52
+ QuickTalkUtil.working = working;
53
+ /**
54
+ * Where a talk is now, by what the double's page or the agent's session says: it answers once seen at work,
55
+ * and has answered once it stops with a last line that is not what the user said, nor the line it had as
56
+ * the user spoke (`baseline`; without one, a line later than the talk, by the clock).
57
+ */
58
+ function next(talk, now, at = Date.now()) {
59
+ if (talk.phase !== 'waiting' && talk.phase !== 'answering') {
60
+ return undefined;
61
+ }
62
+ if (now.busy) {
63
+ return talk.phase === 'answering' ? undefined : { phase: 'answering' };
64
+ }
65
+ const line = now.line;
66
+ const fresh = !!line && (talk.baseline ? line.at !== talk.baseline.at || line.text !== talk.baseline.text : line.at > talk.sentAt);
67
+ const answered = fresh && !!line && line.text.trim() !== talk.said.trim();
68
+ if (answered || (talk.phase === 'answering' && line)) {
69
+ return { phase: 'done', reply: line === null || line === void 0 ? void 0 : line.text };
70
+ }
71
+ if (at - talk.sentAt > WAIT_MS) {
72
+ return { phase: 'done' };
73
+ }
74
+ return undefined;
75
+ }
76
+ QuickTalkUtil.next = next;
77
+ })(QuickTalkUtil || (QuickTalkUtil = {}));
78
+ export function useQuickTalk(pi, { agents, sessions, double, oldService, tag }) {
79
+ var _a;
80
+ const React = pi.React;
81
+ const [talks, setTalks] = React.useState([]);
82
+ const [speaking, setSpeaking] = React.useState(false);
83
+ const [listening, setListening] = React.useState();
84
+ const talk = talks[talks.length - 1];
85
+ const current = React.useRef(talk);
86
+ current.current = talk;
87
+ const voice = pi.ui.voice;
88
+ const speak = React.useCallback((text) => {
89
+ if (voice === null || voice === void 0 ? void 0 : voice.canSpeak()) {
90
+ setSpeaking(true);
91
+ voice.speak(text, () => setSpeaking(false));
92
+ }
93
+ }, [voice]);
94
+ const hush = React.useCallback(() => {
95
+ voice === null || voice === void 0 ? void 0 : voice.hush();
96
+ setSpeaking(false);
97
+ }, [voice]);
98
+ // Reading stops with the town.
99
+ React.useEffect(() => () => voice === null || voice === void 0 ? void 0 : voice.hush(), [voice]);
100
+ const update = React.useCallback((change, sentAt) => setTalks(before => before.map(each =>
101
+ // A talk said over by a newer one stays done.
102
+ each.sentAt !== sentAt || (each.phase === 'done' && change.phase === 'waiting') ? each : { ...each, ...change })), []);
103
+ const send = React.useCallback((target, text, byVoice) => {
104
+ var _a;
105
+ var _b;
106
+ const said = text.trim();
107
+ if (!said) {
108
+ return;
109
+ }
110
+ const sentAt = Math.max(Date.now(), ((_b = (_a = current.current) === null || _a === void 0 ? void 0 : _a.sentAt) !== null && _b !== void 0 ? _b : 0) + 1);
111
+ voice === null || voice === void 0 ? void 0 : voice.hush();
112
+ setSpeaking(false);
113
+ const agent = target.agent;
114
+ const open = (agent === null || agent === void 0 ? void 0 : agent.sessionFile) ? sessions.find(session => session.sessionFile === agent.sessionFile) : undefined;
115
+ const baseline = target.kind === 'double' ? double === null || double === void 0 ? void 0 : double.preview : (open === null || open === void 0 ? void 0 : open.lastMessage) ? { text: open.lastMessage, at: open.updatedAt } : undefined;
116
+ const talk = { to: target.to, kind: target.kind, said, voice: byVoice, sentAt, phase: 'sending', baseline };
117
+ // What the one talked to has not answered yet is said over: the answer that comes is to the newest.
118
+ setTalks(before => [...before.map(each => (each.to === target.to && QuickTalkUtil.working(each) ? { ...each, phase: 'done' } : each)), talk].slice(-KEPT));
119
+ const go = async () => {
120
+ var _a;
121
+ if (target.kind === 'double') {
122
+ if (double === null || double === void 0 ? void 0 : double.send) {
123
+ await double.send(said);
124
+ }
125
+ else {
126
+ await pi.ui.showView(DOUBLE_PAGE);
127
+ await pi.sendUserMessage(said);
128
+ }
129
+ update({ phase: 'waiting' }, sentAt);
130
+ }
131
+ else if (target.kind === 'room' && target.channelId) {
132
+ await askChannels(pi, { kind: 'post', channel: target.channelId, text: said });
133
+ update({ phase: 'done' }, sentAt);
134
+ }
135
+ else if (agent) {
136
+ const sessionId = (_a = open === null || open === void 0 ? void 0 : open.sessionId) !== null && _a !== void 0 ? _a : (await agentSession(pi, agent.id, oldService));
137
+ update({ sessionId }, sentAt);
138
+ await pi.server.prompt(sessionId, {
139
+ message: said,
140
+ clientMessageId: `${tag}-${sentAt.toString(36)}-${Math.random().toString(36).slice(2, 8)}`,
141
+ streamingBehavior: 'followUp',
142
+ });
143
+ update({ phase: 'waiting' }, sentAt);
144
+ }
145
+ };
146
+ go().catch(error => update({ phase: 'failed', error: error instanceof Error ? error.message : String(error) }, sentAt));
147
+ }, [pi, voice, double, sessions, update, oldService, tag]);
148
+ /** What was sent last was said by voice (the box held to talk): its answer is read aloud. */
149
+ const spoken = React.useCallback(() => {
150
+ const last = current.current;
151
+ if (last) {
152
+ update({ voice: true }, last.sentAt);
153
+ }
154
+ }, [update]);
155
+ /** Stops an agent that answers; the double's page has no stop of its own. */
156
+ const stop = React.useCallback(() => {
157
+ const last = current.current;
158
+ if ((last === null || last === void 0 ? void 0 : last.sessionId) && QuickTalkUtil.working(last)) {
159
+ pi.server.abort(last.sessionId).catch(() => undefined);
160
+ }
161
+ }, [pi]);
162
+ // The answer as it comes: from the double's page, or the agent's session.
163
+ const session = (talk === null || talk === void 0 ? void 0 : talk.sessionId) ? sessions.find(each => each.sessionId === talk.sessionId) : undefined;
164
+ const now = (talk === null || talk === void 0 ? void 0 : talk.kind) === 'double'
165
+ ? { busy: !!(double === null || double === void 0 ? void 0 : double.busy), line: double === null || double === void 0 ? void 0 : double.preview }
166
+ : session
167
+ ? { busy: session.isStreaming, line: session.lastMessage ? { text: session.lastMessage, at: session.updatedAt } : undefined }
168
+ : undefined;
169
+ const step = talk && now ? QuickTalkUtil.next(talk, now) : undefined;
170
+ const stepKey = step ? `${step.phase}:${(_a = step.reply) !== null && _a !== void 0 ? _a : ''}` : '';
171
+ const latest = React.useRef({ sessions, session });
172
+ latest.current = { sessions, session };
173
+ // Again when `stepKey` changes, which says all of `step` (a new object at each drawing).
174
+ React.useEffect(() => {
175
+ var _a;
176
+ var _b;
177
+ const before = current.current;
178
+ if (!step || !before) {
179
+ return;
180
+ }
181
+ update(step, before.sentAt);
182
+ if (step.phase !== 'done' || !step.reply) {
183
+ return;
184
+ }
185
+ // A list shows the last line on one line: the answer in full, as written, comes from its session.
186
+ const line = step.reply;
187
+ const sessionId = (_b = before.sessionId) !== null && _b !== void 0 ? _b : (_a = latest.current.sessions.find(each => !each.isStreaming && each.lastMessage === line && each.updatedAt > before.sentAt)) === null || _a === void 0 ? void 0 : _a.sessionId;
188
+ const full = sessionId
189
+ ? pi.server.getLastAssistantText(sessionId).then(result => (result === null || result === void 0 ? void 0 : result.text) || line, () => line)
190
+ : Promise.resolve(line);
191
+ full.then(text => {
192
+ var _a;
193
+ if (text !== line) {
194
+ update({ reply: text }, before.sentAt);
195
+ }
196
+ if (before.voice || ((_a = current.current) === null || _a === void 0 ? void 0 : _a.voice)) {
197
+ speak(text);
198
+ }
199
+ });
200
+ }, [stepKey, speak, update, pi]);
201
+ // An agent the user talks to that is not in the team anymore: its talks end.
202
+ React.useEffect(() => {
203
+ const gone = (each) => each.kind === 'agent' && !agents.some(agent => agent.id === each.to);
204
+ if (talks.some(gone)) {
205
+ setTalks(before => before.filter(each => !gone(each)));
206
+ }
207
+ }, [talks, agents]);
208
+ return {
209
+ talk,
210
+ talks,
211
+ speaking,
212
+ listening,
213
+ send,
214
+ spoken,
215
+ stop,
216
+ speak,
217
+ hush,
218
+ /** Whom the user holds the box to talk to, or none. */
219
+ listen: setListening,
220
+ clear: () => setTalks([]),
221
+ };
222
+ }
223
+ //# sourceMappingURL=quick-talk.js.map
package/lib/index.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ export * from './quick-talk';
2
+ //# sourceMappingURL=index.d.ts.map
package/lib/index.js ADDED
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./quick-talk"), exports);
18
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,94 @@
1
+ import type { TaSessionInfo } from '@celljs/ta-protocol';
2
+ import type { WebExtensionAPI, WebViewInfo } from '@celljs/ta-web/lib/browser/extension/web-extension-api';
3
+ /** The double's page. */
4
+ export declare const DOUBLE_PAGE = "assistant/assistant";
5
+ export type QuickTalkPhase = 'sending' | 'waiting' | 'answering' | 'done' | 'failed';
6
+ export interface QuickTalk {
7
+ /** A resident's id, or a meeting room's place id. */
8
+ to: string;
9
+ kind: 'double' | 'agent' | 'room';
10
+ said: string;
11
+ /** Said by voice: the answer is read aloud. */
12
+ voice: boolean;
13
+ sentAt: number;
14
+ phase: QuickTalkPhase;
15
+ sessionId?: string;
16
+ /** The last line of the one talked to as the user spoke: an answer is a line after it. */
17
+ baseline?: {
18
+ text: string;
19
+ at: number;
20
+ };
21
+ reply?: string;
22
+ error?: string;
23
+ }
24
+ /** An agent as a page knows it: its session file, when it has one open. */
25
+ export interface QuickTalkAgent {
26
+ id: string;
27
+ sessionFile?: string;
28
+ }
29
+ export interface QuickTalkTarget {
30
+ to: string;
31
+ kind: QuickTalk['kind'];
32
+ agent?: QuickTalkAgent;
33
+ channelId?: string;
34
+ }
35
+ export interface QuickTalkOptions {
36
+ /** The agents of the user's team, as the page has them. */
37
+ agents: readonly QuickTalkAgent[];
38
+ sessions: readonly TaSessionInfo[];
39
+ /** The double's page (`ui.useView(DOUBLE_PAGE)`). */
40
+ double: WebViewInfo | undefined;
41
+ /** What is said when the Ta service is too old to open an agent's session. */
42
+ oldService: string;
43
+ /** Marks the messages sent (`clientMessageId`), by the page: `town`, `earth`. */
44
+ tag: string;
45
+ }
46
+ /** A request to ta-channels' host. */
47
+ export declare function askChannels(pi: WebExtensionAPI, request: Record<string, unknown>): Promise<unknown>;
48
+ /**
49
+ * The session of an agent, opened by ta-channels if it is not. A Ta service started before its pages called it
50
+ * (14 Nov 2026) answers nothing: the user is told `oldService` rather than shown a TypeError.
51
+ */
52
+ export declare function agentSession(pi: WebExtensionAPI, agentId: string, oldService: string): Promise<string>;
53
+ export declare namespace QuickTalkUtil {
54
+ /**
55
+ * Whom a talk is with, as the model shows it: standing and listening while the user talks to it or waits,
56
+ * then answering. `listening`: whom the user holds the box to talk to now.
57
+ */
58
+ function talking(talk: QuickTalk | undefined, listening?: string): {
59
+ id: string;
60
+ answering: boolean;
61
+ } | undefined;
62
+ /** The talks with one, the last `count` of them, oldest first. */
63
+ function thread(talks: readonly QuickTalk[], to: string, count?: number): QuickTalk[];
64
+ /** Whether one is still answering: the send button stops it then. */
65
+ function working(talk: QuickTalk | undefined): boolean;
66
+ /**
67
+ * Where a talk is now, by what the double's page or the agent's session says: it answers once seen at work,
68
+ * and has answered once it stops with a last line that is not what the user said, nor the line it had as
69
+ * the user spoke (`baseline`; without one, a line later than the talk, by the clock).
70
+ */
71
+ function next(talk: QuickTalk, now: {
72
+ busy: boolean;
73
+ line?: {
74
+ text: string;
75
+ at: number;
76
+ };
77
+ }, at?: number): Pick<QuickTalk, 'phase' | 'reply'> | undefined;
78
+ }
79
+ export declare function useQuickTalk(pi: WebExtensionAPI, { agents, sessions, double, oldService, tag }: QuickTalkOptions): {
80
+ talk: QuickTalk;
81
+ talks: QuickTalk[];
82
+ speaking: boolean;
83
+ listening: string | undefined;
84
+ send: (target: QuickTalkTarget, text: string, byVoice: boolean) => void;
85
+ spoken: () => void;
86
+ stop: () => void;
87
+ speak: (text: string) => void;
88
+ hush: () => void;
89
+ /** Whom the user holds the box to talk to, or none. */
90
+ listen: import("react").Dispatch<import("react").SetStateAction<string | undefined>>;
91
+ clear: () => void;
92
+ };
93
+ export type QuickTalkState = ReturnType<typeof useQuickTalk>;
94
+ //# sourceMappingURL=quick-talk.d.ts.map
@@ -0,0 +1,229 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.QuickTalkUtil = exports.DOUBLE_PAGE = void 0;
4
+ exports.askChannels = askChannels;
5
+ exports.agentSession = agentSession;
6
+ exports.useQuickTalk = useQuickTalk;
7
+ // Talking to the double or an agent from a page of play without leaving it (useQuickTalk; the town, Block Earth): what
8
+ // the user says (typed, or held to talk) goes to the double (its page's `send`), to an agent's own session, or into a
9
+ // channel; the page shows the talk as a short thread, the answer in full once it is written, and reads it aloud when
10
+ // the user talked by voice. One for every page that has the user's Ta in it, so that they all talk the same way.
11
+ const CHANNELS = '@celljs/ta-channels';
12
+ /** The double's page. */
13
+ exports.DOUBLE_PAGE = 'assistant/assistant';
14
+ /** Past that, an answer that never came is no longer waited for. */
15
+ const WAIT_MS = 5 * 60000;
16
+ /** Talks kept, of all the residents. */
17
+ const KEPT = 24;
18
+ /** A request to ta-channels' host. */
19
+ function askChannels(pi, request) {
20
+ return pi.packages.callPackageHost(CHANNELS, 'request', [request]);
21
+ }
22
+ /**
23
+ * The session of an agent, opened by ta-channels if it is not. A Ta service started before its pages called it
24
+ * (14 Nov 2026) answers nothing: the user is told `oldService` rather than shown a TypeError.
25
+ */
26
+ async function agentSession(pi, agentId, oldService) {
27
+ const answer = (await askChannels(pi, { kind: 'openAgent', agent: agentId }));
28
+ if (typeof (answer === null || answer === void 0 ? void 0 : answer.sessionId) !== 'string' || !answer.sessionId) {
29
+ throw new Error(oldService);
30
+ }
31
+ return answer.sessionId;
32
+ }
33
+ var QuickTalkUtil;
34
+ (function (QuickTalkUtil) {
35
+ /**
36
+ * Whom a talk is with, as the model shows it: standing and listening while the user talks to it or waits,
37
+ * then answering. `listening`: whom the user holds the box to talk to now.
38
+ */
39
+ function talking(talk, listening) {
40
+ if (listening && !listening.startsWith('room:')) {
41
+ return { id: listening, answering: false };
42
+ }
43
+ if (!talk || talk.kind === 'room' || talk.phase === 'done' || talk.phase === 'failed') {
44
+ return undefined;
45
+ }
46
+ return { id: talk.to, answering: talk.phase === 'answering' };
47
+ }
48
+ QuickTalkUtil.talking = talking;
49
+ /** The talks with one, the last `count` of them, oldest first. */
50
+ function thread(talks, to, count = 6) {
51
+ return talks.filter(talk => talk.to === to).slice(-count);
52
+ }
53
+ QuickTalkUtil.thread = thread;
54
+ /** Whether one is still answering: the send button stops it then. */
55
+ function working(talk) {
56
+ return !!talk && (talk.phase === 'sending' || talk.phase === 'waiting' || talk.phase === 'answering');
57
+ }
58
+ QuickTalkUtil.working = working;
59
+ /**
60
+ * Where a talk is now, by what the double's page or the agent's session says: it answers once seen at work,
61
+ * and has answered once it stops with a last line that is not what the user said, nor the line it had as
62
+ * the user spoke (`baseline`; without one, a line later than the talk, by the clock).
63
+ */
64
+ function next(talk, now, at = Date.now()) {
65
+ if (talk.phase !== 'waiting' && talk.phase !== 'answering') {
66
+ return undefined;
67
+ }
68
+ if (now.busy) {
69
+ return talk.phase === 'answering' ? undefined : { phase: 'answering' };
70
+ }
71
+ const line = now.line;
72
+ const fresh = !!line && (talk.baseline ? line.at !== talk.baseline.at || line.text !== talk.baseline.text : line.at > talk.sentAt);
73
+ const answered = fresh && !!line && line.text.trim() !== talk.said.trim();
74
+ if (answered || (talk.phase === 'answering' && line)) {
75
+ return { phase: 'done', reply: line === null || line === void 0 ? void 0 : line.text };
76
+ }
77
+ if (at - talk.sentAt > WAIT_MS) {
78
+ return { phase: 'done' };
79
+ }
80
+ return undefined;
81
+ }
82
+ QuickTalkUtil.next = next;
83
+ })(QuickTalkUtil || (exports.QuickTalkUtil = QuickTalkUtil = {}));
84
+ function useQuickTalk(pi, { agents, sessions, double, oldService, tag }) {
85
+ var _a;
86
+ const React = pi.React;
87
+ const [talks, setTalks] = React.useState([]);
88
+ const [speaking, setSpeaking] = React.useState(false);
89
+ const [listening, setListening] = React.useState();
90
+ const talk = talks[talks.length - 1];
91
+ const current = React.useRef(talk);
92
+ current.current = talk;
93
+ const voice = pi.ui.voice;
94
+ const speak = React.useCallback((text) => {
95
+ if (voice === null || voice === void 0 ? void 0 : voice.canSpeak()) {
96
+ setSpeaking(true);
97
+ voice.speak(text, () => setSpeaking(false));
98
+ }
99
+ }, [voice]);
100
+ const hush = React.useCallback(() => {
101
+ voice === null || voice === void 0 ? void 0 : voice.hush();
102
+ setSpeaking(false);
103
+ }, [voice]);
104
+ // Reading stops with the town.
105
+ React.useEffect(() => () => voice === null || voice === void 0 ? void 0 : voice.hush(), [voice]);
106
+ const update = React.useCallback((change, sentAt) => setTalks(before => before.map(each =>
107
+ // A talk said over by a newer one stays done.
108
+ each.sentAt !== sentAt || (each.phase === 'done' && change.phase === 'waiting') ? each : { ...each, ...change })), []);
109
+ const send = React.useCallback((target, text, byVoice) => {
110
+ var _a;
111
+ var _b;
112
+ const said = text.trim();
113
+ if (!said) {
114
+ return;
115
+ }
116
+ const sentAt = Math.max(Date.now(), ((_b = (_a = current.current) === null || _a === void 0 ? void 0 : _a.sentAt) !== null && _b !== void 0 ? _b : 0) + 1);
117
+ voice === null || voice === void 0 ? void 0 : voice.hush();
118
+ setSpeaking(false);
119
+ const agent = target.agent;
120
+ const open = (agent === null || agent === void 0 ? void 0 : agent.sessionFile) ? sessions.find(session => session.sessionFile === agent.sessionFile) : undefined;
121
+ const baseline = target.kind === 'double' ? double === null || double === void 0 ? void 0 : double.preview : (open === null || open === void 0 ? void 0 : open.lastMessage) ? { text: open.lastMessage, at: open.updatedAt } : undefined;
122
+ const talk = { to: target.to, kind: target.kind, said, voice: byVoice, sentAt, phase: 'sending', baseline };
123
+ // What the one talked to has not answered yet is said over: the answer that comes is to the newest.
124
+ setTalks(before => [...before.map(each => (each.to === target.to && QuickTalkUtil.working(each) ? { ...each, phase: 'done' } : each)), talk].slice(-KEPT));
125
+ const go = async () => {
126
+ var _a;
127
+ if (target.kind === 'double') {
128
+ if (double === null || double === void 0 ? void 0 : double.send) {
129
+ await double.send(said);
130
+ }
131
+ else {
132
+ await pi.ui.showView(exports.DOUBLE_PAGE);
133
+ await pi.sendUserMessage(said);
134
+ }
135
+ update({ phase: 'waiting' }, sentAt);
136
+ }
137
+ else if (target.kind === 'room' && target.channelId) {
138
+ await askChannels(pi, { kind: 'post', channel: target.channelId, text: said });
139
+ update({ phase: 'done' }, sentAt);
140
+ }
141
+ else if (agent) {
142
+ const sessionId = (_a = open === null || open === void 0 ? void 0 : open.sessionId) !== null && _a !== void 0 ? _a : (await agentSession(pi, agent.id, oldService));
143
+ update({ sessionId }, sentAt);
144
+ await pi.server.prompt(sessionId, {
145
+ message: said,
146
+ clientMessageId: `${tag}-${sentAt.toString(36)}-${Math.random().toString(36).slice(2, 8)}`,
147
+ streamingBehavior: 'followUp',
148
+ });
149
+ update({ phase: 'waiting' }, sentAt);
150
+ }
151
+ };
152
+ go().catch(error => update({ phase: 'failed', error: error instanceof Error ? error.message : String(error) }, sentAt));
153
+ }, [pi, voice, double, sessions, update, oldService, tag]);
154
+ /** What was sent last was said by voice (the box held to talk): its answer is read aloud. */
155
+ const spoken = React.useCallback(() => {
156
+ const last = current.current;
157
+ if (last) {
158
+ update({ voice: true }, last.sentAt);
159
+ }
160
+ }, [update]);
161
+ /** Stops an agent that answers; the double's page has no stop of its own. */
162
+ const stop = React.useCallback(() => {
163
+ const last = current.current;
164
+ if ((last === null || last === void 0 ? void 0 : last.sessionId) && QuickTalkUtil.working(last)) {
165
+ pi.server.abort(last.sessionId).catch(() => undefined);
166
+ }
167
+ }, [pi]);
168
+ // The answer as it comes: from the double's page, or the agent's session.
169
+ const session = (talk === null || talk === void 0 ? void 0 : talk.sessionId) ? sessions.find(each => each.sessionId === talk.sessionId) : undefined;
170
+ const now = (talk === null || talk === void 0 ? void 0 : talk.kind) === 'double'
171
+ ? { busy: !!(double === null || double === void 0 ? void 0 : double.busy), line: double === null || double === void 0 ? void 0 : double.preview }
172
+ : session
173
+ ? { busy: session.isStreaming, line: session.lastMessage ? { text: session.lastMessage, at: session.updatedAt } : undefined }
174
+ : undefined;
175
+ const step = talk && now ? QuickTalkUtil.next(talk, now) : undefined;
176
+ const stepKey = step ? `${step.phase}:${(_a = step.reply) !== null && _a !== void 0 ? _a : ''}` : '';
177
+ const latest = React.useRef({ sessions, session });
178
+ latest.current = { sessions, session };
179
+ // Again when `stepKey` changes, which says all of `step` (a new object at each drawing).
180
+ React.useEffect(() => {
181
+ var _a;
182
+ var _b;
183
+ const before = current.current;
184
+ if (!step || !before) {
185
+ return;
186
+ }
187
+ update(step, before.sentAt);
188
+ if (step.phase !== 'done' || !step.reply) {
189
+ return;
190
+ }
191
+ // A list shows the last line on one line: the answer in full, as written, comes from its session.
192
+ const line = step.reply;
193
+ const sessionId = (_b = before.sessionId) !== null && _b !== void 0 ? _b : (_a = latest.current.sessions.find(each => !each.isStreaming && each.lastMessage === line && each.updatedAt > before.sentAt)) === null || _a === void 0 ? void 0 : _a.sessionId;
194
+ const full = sessionId
195
+ ? pi.server.getLastAssistantText(sessionId).then(result => (result === null || result === void 0 ? void 0 : result.text) || line, () => line)
196
+ : Promise.resolve(line);
197
+ full.then(text => {
198
+ var _a;
199
+ if (text !== line) {
200
+ update({ reply: text }, before.sentAt);
201
+ }
202
+ if (before.voice || ((_a = current.current) === null || _a === void 0 ? void 0 : _a.voice)) {
203
+ speak(text);
204
+ }
205
+ });
206
+ }, [stepKey, speak, update, pi]);
207
+ // An agent the user talks to that is not in the team anymore: its talks end.
208
+ React.useEffect(() => {
209
+ const gone = (each) => each.kind === 'agent' && !agents.some(agent => agent.id === each.to);
210
+ if (talks.some(gone)) {
211
+ setTalks(before => before.filter(each => !gone(each)));
212
+ }
213
+ }, [talks, agents]);
214
+ return {
215
+ talk,
216
+ talks,
217
+ speaking,
218
+ listening,
219
+ send,
220
+ spoken,
221
+ stop,
222
+ speak,
223
+ hush,
224
+ /** Whom the user holds the box to talk to, or none. */
225
+ listen: setListening,
226
+ clear: () => setTalks([]),
227
+ };
228
+ }
229
+ //# sourceMappingURL=quick-talk.js.map
package/package.json CHANGED
@@ -1,6 +1,51 @@
1
1
  {
2
2
  "name": "@celljs/ta-quick-talk",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "4.44.0",
4
+ "description": "Talking to the user's Ta from a page of play without leaving it (the town, Block Earth): to the double, an agent of ta-channels or a channel, the answer shown and read aloud",
5
+ "homepage": "https://github.com/cellbang/ta",
6
+ "bugs": {
7
+ "url": "https://github.com/cellbang/ta/issues"
8
+ },
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "https://github.com/cellbang/cell.git"
12
+ },
13
+ "license": "MIT",
14
+ "main": "lib/index.js",
15
+ "typings": "lib/index.d.ts",
16
+ "files": [
17
+ "lib",
18
+ "esm",
19
+ "!lib/**/*.spec.*",
20
+ "!**/*.map"
21
+ ],
22
+ "scripts": {
23
+ "build": "tsc -b && bun ../../scripts/build-esm.ts",
24
+ "clean": "rm -rf lib esm *.tsbuildinfo",
25
+ "test": "bun test ./lib",
26
+ "watch": "tsc -b -w --preserveWatchOutput"
27
+ },
28
+ "devDependencies": {
29
+ "@celljs/ta-protocol": "4.44.0",
30
+ "@celljs/ta-web": "4.44.0"
31
+ },
32
+ "publishConfig": {
33
+ "access": "public"
34
+ },
35
+ "exports": {
36
+ ".": {
37
+ "import": "./esm/index.js",
38
+ "default": "./lib/index.js"
39
+ },
40
+ "./package.json": "./package.json",
41
+ "./lib/*.js": {
42
+ "import": "./esm/*.js",
43
+ "default": "./lib/*.js"
44
+ },
45
+ "./lib/*": {
46
+ "import": "./esm/*.js",
47
+ "default": "./lib/*.js"
48
+ },
49
+ "./*": "./*"
50
+ }
51
+ }