@celljs/ta-host 4.14.0 → 4.15.1

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 (55) hide show
  1. package/README.en.md +2 -1
  2. package/README.md +2 -1
  3. package/esm/node/auth-server-impl.d.ts +12 -2
  4. package/esm/node/auth-server-impl.js +102 -3
  5. package/esm/node/custom-providers.d.ts +50 -0
  6. package/esm/node/custom-providers.js +335 -0
  7. package/esm/node/extension-data.js +7 -3
  8. package/esm/node/index.d.ts +1 -0
  9. package/esm/node/index.js +1 -0
  10. package/esm/node/jpeg-encoder.d.ts +7 -0
  11. package/esm/node/jpeg-encoder.js +268 -0
  12. package/esm/node/png-thumbnail.d.ts +40 -0
  13. package/esm/node/png-thumbnail.js +384 -0
  14. package/esm/node/serve-updates.d.ts +38 -0
  15. package/esm/node/serve-updates.js +89 -0
  16. package/esm/node/sign-in/sign-in-provider.d.ts +44 -0
  17. package/esm/node/sign-in/sign-in-provider.js +74 -7
  18. package/esm/node/sign-in/ta-sign-in.d.ts +4 -1
  19. package/esm/node/sign-in/ta-sign-in.js +6 -2
  20. package/esm/node/ta-server-impl.d.ts +3 -0
  21. package/esm/node/ta-server-impl.js +33 -9
  22. package/esm/node/team/host-team.js +1 -0
  23. package/esm/node/team/member-accounts.d.ts +25 -8
  24. package/esm/node/team/member-accounts.js +84 -4
  25. package/esm/node/team/team-calls.js +5 -0
  26. package/esm/node/web-extension-util.js +1 -0
  27. package/esm/node/workspace-files.d.ts +23 -0
  28. package/esm/node/workspace-files.js +86 -0
  29. package/lib/node/auth-server-impl.d.ts +12 -2
  30. package/lib/node/auth-server-impl.js +101 -2
  31. package/lib/node/custom-providers.d.ts +51 -0
  32. package/lib/node/custom-providers.js +338 -0
  33. package/lib/node/extension-data.js +6 -2
  34. package/lib/node/index.d.ts +1 -0
  35. package/lib/node/index.js +1 -0
  36. package/lib/node/jpeg-encoder.d.ts +8 -0
  37. package/lib/node/jpeg-encoder.js +271 -0
  38. package/lib/node/png-thumbnail.d.ts +41 -0
  39. package/lib/node/png-thumbnail.js +387 -0
  40. package/lib/node/serve-updates.d.ts +39 -0
  41. package/lib/node/serve-updates.js +92 -0
  42. package/lib/node/sign-in/sign-in-provider.d.ts +44 -0
  43. package/lib/node/sign-in/sign-in-provider.js +77 -9
  44. package/lib/node/sign-in/ta-sign-in.d.ts +4 -1
  45. package/lib/node/sign-in/ta-sign-in.js +6 -2
  46. package/lib/node/ta-server-impl.d.ts +3 -0
  47. package/lib/node/ta-server-impl.js +33 -9
  48. package/lib/node/team/host-team.js +1 -0
  49. package/lib/node/team/member-accounts.d.ts +25 -8
  50. package/lib/node/team/member-accounts.js +84 -4
  51. package/lib/node/team/team-calls.js +5 -0
  52. package/lib/node/web-extension-util.js +1 -0
  53. package/lib/node/workspace-files.d.ts +23 -0
  54. package/lib/node/workspace-files.js +86 -0
  55. package/package.json +10 -10
@@ -44,7 +44,22 @@ export class GitHubSignIn {
44
44
  static endpoints(url = 'https://github.com') {
45
45
  const base = url.replace(/\/+$/, '');
46
46
  const api = base === 'https://github.com' ? 'https://api.github.com' : `${base}/api/v3`;
47
- return { authorize: `${base}/login/oauth/authorize`, token: `${base}/login/oauth/access_token`, user: `${api}/user` };
47
+ return {
48
+ authorize: `${base}/login/oauth/authorize`,
49
+ token: `${base}/login/oauth/access_token`,
50
+ user: `${api}/user`,
51
+ device: `${base}/login/device/code`,
52
+ };
53
+ }
54
+ /** Who a token of GitHub is. */
55
+ static async user(endpoints, token) {
56
+ const user = await SignInHttp.json(endpoints.user, {
57
+ headers: { Authorization: `Bearer ${token}`, Accept: 'application/vnd.github+json', 'User-Agent': 'Ta' },
58
+ });
59
+ if (!user.login) {
60
+ throw new SignInError('GitHub: the user has no login');
61
+ }
62
+ return { id: `github:${user.login.toLowerCase()}`, name: user.name || user.login, avatar: user.avatar_url };
48
63
  }
49
64
  constructor(clientId, clientSecret, endpoints = GitHubSignIn.endpoints()) {
50
65
  this.clientId = clientId;
@@ -70,15 +85,49 @@ export class GitHubSignIn {
70
85
  if (!token.access_token) {
71
86
  throw new SignInError(`GitHub: ${(_b = (_a = token.error_description) !== null && _a !== void 0 ? _a : token.error) !== null && _b !== void 0 ? _b : 'no access token'}`);
72
87
  }
73
- const user = await SignInHttp.json(this.endpoints.user, {
74
- headers: { Authorization: `Bearer ${token.access_token}`, Accept: 'application/vnd.github+json', 'User-Agent': 'Ta' },
75
- });
76
- if (!user.login) {
77
- throw new SignInError('GitHub: the user has no login');
88
+ return GitHubSignIn.user(this.endpoints, token.access_token);
89
+ }
90
+ }
91
+ /** GitHub's device flow, with Ta's own OAuth app by default; the account is `github:<login>`, as GitHubSignIn's. */
92
+ export class GitHubDeviceSignIn {
93
+ constructor(clientId = GitHubDeviceSignIn.CLIENT_ID, endpoints = GitHubSignIn.endpoints()) {
94
+ this.clientId = clientId;
95
+ this.endpoints = endpoints;
96
+ this.id = 'github';
97
+ this.name = 'GitHub';
98
+ this.device = true;
99
+ }
100
+ async code() {
101
+ var _a, _b, _c, _d;
102
+ const answer = await SignInHttp.json(this.endpoints.device, SignInHttp.form({ client_id: this.clientId, scope: 'read:user' }));
103
+ if (!answer.device_code || !answer.user_code || !answer.verification_uri || !/^https?:\/\//.test(answer.verification_uri)) {
104
+ throw new SignInError(`GitHub: ${(_b = (_a = answer.error_description) !== null && _a !== void 0 ? _a : answer.error) !== null && _b !== void 0 ? _b : 'no code'}`);
78
105
  }
79
- return { id: `github:${user.login.toLowerCase()}`, name: user.name || user.login, avatar: user.avatar_url };
106
+ return {
107
+ deviceCode: answer.device_code,
108
+ userCode: answer.user_code,
109
+ uri: answer.verification_uri,
110
+ interval: Number((_c = answer.interval) !== null && _c !== void 0 ? _c : 5),
111
+ expiresIn: Number((_d = answer.expires_in) !== null && _d !== void 0 ? _d : 900),
112
+ };
113
+ }
114
+ async poll(deviceCode) {
115
+ var _a, _b;
116
+ const token = await SignInHttp.json(this.endpoints.token, SignInHttp.form({ client_id: this.clientId, device_code: deviceCode, grant_type: 'urn:ietf:params:oauth:grant-type:device_code' }));
117
+ if (token.access_token) {
118
+ return GitHubSignIn.user(this.endpoints, token.access_token);
119
+ }
120
+ if (token.error === 'authorization_pending') {
121
+ return 'pending';
122
+ }
123
+ if (token.error === 'slow_down') {
124
+ return 'slowDown';
125
+ }
126
+ throw new SignInError(`GitHub: ${(_b = (_a = token.error_description) !== null && _a !== void 0 ? _a : token.error) !== null && _b !== void 0 ? _b : 'no access token'}`);
80
127
  }
81
128
  }
129
+ /** Ta's own OAuth app on GitHub.com, its device flow on: a client id is public, and the device flow needs no secret. */
130
+ GitHubDeviceSignIn.CLIENT_ID = 'Ov23lip46sRQDlDM1xt7';
82
131
  /**
83
132
  * OpenID Connect, found from the issuer (`/.well-known/openid-configuration`): Google, and the provider of
84
133
  * the operator (Microsoft Entra, Okta, Keycloak, Authing...). The account is `<id>:<email>` when the
@@ -315,6 +364,24 @@ export var SignInProviders;
315
364
  return merged;
316
365
  }
317
366
  SignInProviders.withConfig = withConfig;
367
+ /**
368
+ * GitHub by a code, for those asking to come in, when GitHub is not set up with its secret (which goes there and back
369
+ * instead): `TA_GITHUB_DEVICE` is `off`, or `<client id>` or `<client id>@<address of GitHub>` of an OAuth app of
370
+ * one's own with its device flow on; by default Ta's own, on GitHub.com.
371
+ */
372
+ function device(env) {
373
+ var _a;
374
+ var _b;
375
+ const value = (_b = (_a = env.TA_GITHUB_DEVICE) === null || _a === void 0 ? void 0 : _a.trim()) !== null && _b !== void 0 ? _b : '';
376
+ if (value === 'off' || (env.TA_GITHUB_CLIENT_ID && env.TA_GITHUB_CLIENT_SECRET)) {
377
+ return undefined;
378
+ }
379
+ const at = value.indexOf('@');
380
+ const clientId = at < 0 ? value : value.slice(0, at);
381
+ const url = at < 0 ? undefined : value.slice(at + 1);
382
+ return new GitHubDeviceSignIn(clientId || GitHubDeviceSignIn.CLIENT_ID, GitHubSignIn.endpoints(url || undefined));
383
+ }
384
+ SignInProviders.device = device;
318
385
  /**
319
386
  * The providers the operator configured in the environment of ta serve: a provider is offered when it
320
387
  * has its id and its secret.
@@ -1,14 +1,17 @@
1
1
  import type { TaSignInKind, TaSignInSetup } from '@celljs/ta-protocol';
2
2
  import { SignInFlow } from './sign-in-flow.js';
3
+ import { type DeviceSignInProvider } from './sign-in-provider.js';
3
4
  export declare const TA_SIGN_IN: unique symbol;
4
5
  /**
5
6
  * Signing in to ta serve with an account, besides its token. The providers come from the environment, then
6
7
  * sign-in.json of the agent directory (SignInProviders.withConfig), which Settings, Access writes (setProvider) and
7
8
  * which is read again then; who may sign in from TA_ALLOWED_USERS and the accounts added in the web client
8
9
  * (AccessStore). Someone else who signs in is told to wait, and shows up as a request. Those asking to come in by a
9
- * link sign in with the same providers to say who they are (TaHostAccounts), which lets them into nothing.
10
+ * link sign in with the same providers to say who they are (TaHostAccounts), which lets them into nothing, or, when GitHub
11
+ * is not set up, with GitHub by a code, Ta's own app (`device`, SignInProviders.device).
10
12
  */
11
13
  export declare class TaSignIn extends SignInFlow {
14
+ device: DeviceSignInProvider | undefined;
12
15
  constructor();
13
16
  setups(): TaSignInSetup[];
14
17
  /** Sets a kind up in sign-in.json (readable by the user alone), offered at once; not one the environment sets. */
@@ -32,14 +32,17 @@ function config() {
32
32
  * sign-in.json of the agent directory (SignInProviders.withConfig), which Settings, Access writes (setProvider) and
33
33
  * which is read again then; who may sign in from TA_ALLOWED_USERS and the accounts added in the web client
34
34
  * (AccessStore). Someone else who signs in is told to wait, and shows up as a request. Those asking to come in by a
35
- * link sign in with the same providers to say who they are (TaHostAccounts), which lets them into nothing.
35
+ * link sign in with the same providers to say who they are (TaHostAccounts), which lets them into nothing, or, when GitHub
36
+ * is not set up, with GitHub by a code, Ta's own app (`device`, SignInProviders.device).
36
37
  */
37
38
  let TaSignIn = class TaSignIn extends SignInFlow {
38
39
  constructor() {
39
40
  super(SignInProviders.fromEnv(SignInProviders.withConfig(process.env, config())), new AccessStore(join(TaBrand.agentDir(), 'access.json'), AccessUtil.parseList(process.env.TA_ALLOWED_USERS)), SignInProviders.publicUrl(process.env));
41
+ this.device = SignInProviders.device(SignInProviders.withConfig(process.env, config()));
40
42
  }
41
43
  setups() {
42
- return SignInProviders.setups(process.env, config());
44
+ const device = this.device;
45
+ return SignInProviders.setups(process.env, config()).map(setup => ((device === null || device === void 0 ? void 0 : device.id) === setup.id && !setup.configured ? { ...setup, device: true } : setup));
43
46
  }
44
47
  /** Sets a kind up in sign-in.json (readable by the user alone), offered at once; not one the environment sets. */
45
48
  setProvider(id, fields) {
@@ -50,6 +53,7 @@ let TaSignIn = class TaSignIn extends SignInFlow {
50
53
  const next = SignInProviders.withProvider(config(), id, fields);
51
54
  writeFileSync(file(), `${JSON.stringify(next, null, 2)}\n`, { mode: 0o600 });
52
55
  this.providers = SignInProviders.fromEnv(SignInProviders.withConfig(process.env, next));
56
+ this.device = SignInProviders.device(SignInProviders.withConfig(process.env, next));
53
57
  }
54
58
  };
55
59
  TaSignIn = __decorate([
@@ -1,6 +1,7 @@
1
1
  import { ExecEnvironmentFactory } from '@celljs/ta-exec';
2
2
  import { type ImageContent, type RpcExtensionUIResponse, type TaAttachOptions, type TaAttachResult, type TaClientToolResult, type TaCommandResult, type TaForkFileResult, type TaMessagePage, type TaNavigateResult, type TaOpenedSession, type TaOpenSessionOptions, type TaPromptInput, type TaPromptReceipt, type TaSavedSessionInfo, type TaSavedSessionQuery, TaServer, type TaServerInfo, type TaSessionInfo, type TaSlashCommand, type ThinkingLevel } from '@celljs/ta-protocol';
3
3
  import { TaSessionCatalog, TaSessionFactory, TaSessionRegistry } from './host-protocol.js';
4
+ import { TaServeUpdates } from './serve-updates.js';
4
5
  import type { TaSession } from './ta-session.js';
5
6
  import { TaAuthority, TaPrincipals, TaRunActors, TaVisibility } from './team/team-protocol.js';
6
7
  import { TaWorkingDirectory } from './working-directory.js';
@@ -19,7 +20,9 @@ export declare class TaServerImpl implements TaServer {
19
20
  protected readonly principals: TaPrincipals;
20
21
  protected readonly authority: TaAuthority;
21
22
  protected readonly visibility: TaVisibility;
23
+ protected readonly updates: TaServeUpdates;
22
24
  getServerInfo(): Promise<TaServerInfo>;
25
+ restartServer(): Promise<void>;
23
26
  setWorkingDirectory(cwd: string): Promise<TaServerInfo>;
24
27
  openSession({ attach, ...options }: TaOpenSessionOptions): Promise<TaOpenedSession>;
25
28
  closeSession(sessionId: string): Promise<void>;
@@ -14,14 +14,17 @@ import { Autowired } from '@celljs/core';
14
14
  import { Rpc } from '@celljs/rpc';
15
15
  import { RpcContext } from '@celljs/rpc/lib/node';
16
16
  import { ExecEnvironmentFactory } from '@celljs/ta-exec';
17
- import { TaBrand } from '@celljs/ta-harness/lib/node/ta-brand';
17
+ import { TaServeRestart } from '@celljs/ta-harness/lib/node/serve-restart';
18
18
  import { TA_OWNER, TaMessageAuthor, TaServer, } from '@celljs/ta-protocol';
19
19
  import { TaSessionCatalog, TaSessionFactory, TaSessionRegistry } from './host-protocol.js';
20
+ import { TaServeUpdates } from './serve-updates.js';
20
21
  import { SessionInfoUtil } from './session-info-util.js';
21
22
  import { SlashCommandUtil } from './slash-command-util.js';
22
23
  import { TaErrors } from './ta-errors.js';
23
24
  import { TaAuthority, TaPrincipals, TaRunActors, TaVisibility } from './team/team-protocol.js';
24
25
  import { TaWorkingDirectory } from './working-directory.js';
26
+ /** How long restartServer leaves its answer to go out before ta serve stops. */
27
+ const RESTART_DELAY_MS = 200;
25
28
  /**
26
29
  * The sessions of ta serve. Each command of pi's RPC mode does here what it does in pi's `rpc-mode`, which
27
30
  * pi exports only bound to stdio: when pi changes one, change it here too (the spec of TaServer in
@@ -29,14 +32,31 @@ import { TaWorkingDirectory } from './working-directory.js';
29
32
  */
30
33
  let TaServerImpl = class TaServerImpl {
31
34
  async getServerInfo() {
32
- return this.guard(async () => ({
33
- version: TaBrand.version(),
34
- cwd: await this.environments.defaultCwd(),
35
- user: userInfo().username,
36
- host: hostname().replace(/\.local$/, ''),
37
- home: homedir(),
38
- ...(this.member() ? { member: this.member() } : {}),
39
- }));
35
+ return this.guard(async () => {
36
+ const { version, build } = this.updates.running();
37
+ const member = this.member();
38
+ // Restarting is the owner's: one let in is not told of it.
39
+ const update = member ? undefined : this.updates.update();
40
+ return {
41
+ version,
42
+ ...(build ? { build } : {}),
43
+ cwd: await this.environments.defaultCwd(),
44
+ user: userInfo().username,
45
+ host: hostname().replace(/\.local$/, ''),
46
+ home: homedir(),
47
+ ...(member ? { member } : { restartable: TaServeRestart.supported() }),
48
+ ...(update ? { update } : {}),
49
+ };
50
+ });
51
+ }
52
+ async restartServer() {
53
+ return this.guard(async () => {
54
+ if (!TaServeRestart.supported()) {
55
+ throw TaErrors.invalidArgument('This Ta service was not started as ta serve, and cannot restart itself.', 'Stop it and start it again where it was started.');
56
+ }
57
+ // Once the answer went out: then the connections close, and connect again to the new one.
58
+ setTimeout(() => TaServeRestart.request(), RESTART_DELAY_MS);
59
+ });
40
60
  }
41
61
  async setWorkingDirectory(cwd) {
42
62
  return this.guard(async () => {
@@ -411,6 +431,10 @@ __decorate([
411
431
  Autowired(TaVisibility),
412
432
  __metadata("design:type", Object)
413
433
  ], TaServerImpl.prototype, "visibility", void 0);
434
+ __decorate([
435
+ Autowired(TaServeUpdates),
436
+ __metadata("design:type", Object)
437
+ ], TaServerImpl.prototype, "updates", void 0);
414
438
  TaServerImpl = __decorate([
415
439
  Rpc(TaServer)
416
440
  ], TaServerImpl);
@@ -35,6 +35,7 @@ let DefaultTaHostTeamProvider = class DefaultTaHostTeamProvider {
35
35
  providers: () => this.accounts.providers(),
36
36
  start: (provider, redirectUri) => this.accounts.start(provider, redirectUri),
37
37
  verify: (state, code) => this.accounts.verify(state, code),
38
+ typed: (state, waitMs) => this.accounts.typed(state, waitMs),
38
39
  },
39
40
  };
40
41
  }
@@ -1,13 +1,30 @@
1
- import type { TaAccount, TaSignInProvider } from '@celljs/ta-protocol';
2
- import type { SignInFlow } from '../sign-in/sign-in-flow.js';
1
+ import type { TaAccount, TaAccountStart, TaSignInProvider } from '@celljs/ta-protocol';
2
+ import { type DeviceSignInProvider, type SignInAccount } from '../sign-in/sign-in-provider.js';
3
+ import { type TaSignIn } from '../sign-in/ta-sign-in.js';
3
4
  import { TaMemberAccounts } from './team-protocol.js';
4
- /** Who one asking to come in is, by an account of the providers ta serve signs in with (TaSignIn): nothing let in by it. */
5
+ /** A sign-in by a code, its device code kept here: who types the code sees it alone. */
6
+ interface Typing {
7
+ provider: DeviceSignInProvider;
8
+ deviceCode: string;
9
+ interval: number;
10
+ next: number;
11
+ expiresAt: number;
12
+ account?: TaAccount;
13
+ }
14
+ /**
15
+ * Who one asking to come in is, by an account of the providers ta serve signs in with (TaSignIn), or by a code typed at
16
+ * GitHub with Ta's own app when GitHub is not set up (TaSignIn.device): nothing let in by it.
17
+ */
5
18
  export declare class DefaultTaMemberAccounts implements TaMemberAccounts {
6
- protected readonly flow: SignInFlow;
19
+ protected readonly flow: TaSignIn;
20
+ protected readonly typing: Map<string, Typing>;
7
21
  providers(): TaSignInProvider[];
8
- start(provider: string, redirectUri: string): Promise<{
9
- url: string;
10
- state: string;
11
- }>;
22
+ start(provider: string, redirectUri: string): Promise<TaAccountStart>;
12
23
  verify(state: string, code: string): Promise<TaAccount>;
24
+ typed(state: string, waitMs?: number): Promise<TaAccount | undefined>;
25
+ /** GitHub by a code, when ta serve has no GitHub of its own. */
26
+ protected device(): DeviceSignInProvider | undefined;
27
+ protected startTyping(device: DeviceSignInProvider): Promise<TaAccountStart>;
28
+ protected of({ id, name, avatar }: SignInAccount): TaAccount;
13
29
  }
30
+ export {};
@@ -7,22 +7,102 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
7
7
  var __metadata = (this && this.__metadata) || function (k, v) {
8
8
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
9
9
  };
10
+ import { randomBytes } from 'node:crypto';
10
11
  import { Autowired, Component } from '@celljs/core';
12
+ import { SignInError } from '../sign-in/sign-in-provider.js';
11
13
  import { TA_SIGN_IN } from '../sign-in/ta-sign-in.js';
12
14
  import { TaMemberAccounts } from './team-protocol.js';
13
- /** Who one asking to come in is, by an account of the providers ta serve signs in with (TaSignIn): nothing let in by it. */
15
+ /** Sign-ins by a code under way at once: anyone holding a link may start one. */
16
+ const MAX_TYPING = 200;
17
+ const WAIT_MS = 25000;
18
+ /**
19
+ * Who one asking to come in is, by an account of the providers ta serve signs in with (TaSignIn), or by a code typed at
20
+ * GitHub with Ta's own app when GitHub is not set up (TaSignIn.device): nothing let in by it.
21
+ */
14
22
  let DefaultTaMemberAccounts = class DefaultTaMemberAccounts {
23
+ constructor() {
24
+ this.typing = new Map();
25
+ }
15
26
  providers() {
16
- return this.flow.providers.map(({ id, name }) => ({ id, name }));
27
+ const own = this.flow.providers.map(({ id, name }) => ({ id, name }));
28
+ const device = this.device();
29
+ return device ? [...own, { id: device.id, name: device.name, device: true }] : own;
17
30
  }
18
- start(provider, redirectUri) {
31
+ async start(provider, redirectUri) {
32
+ const device = this.device();
33
+ if ((device === null || device === void 0 ? void 0 : device.id) === provider) {
34
+ return this.startTyping(device);
35
+ }
19
36
  if (!/^https?:\/\/[^/?#]+\/[^?#]*$/.test(redirectUri)) {
20
37
  throw new Error(`Not an address to come back to: ${redirectUri}`);
21
38
  }
22
39
  return this.flow.startVerify(provider, redirectUri);
23
40
  }
24
41
  async verify(state, code) {
25
- const { id, name, avatar } = await this.flow.verify(state, code);
42
+ return this.of(await this.flow.verify(state, code));
43
+ }
44
+ async typed(state, waitMs = WAIT_MS) {
45
+ const typing = this.typing.get(state);
46
+ if (!typing) {
47
+ throw new SignInError('The sign-in expired or was not started here');
48
+ }
49
+ const until = Date.now() + Math.min(Math.max(0, waitMs), WAIT_MS);
50
+ // Asked no more often than the provider says; one waiting already asks for both.
51
+ while (!typing.account) {
52
+ if (Date.now() >= typing.expiresAt) {
53
+ this.typing.delete(state);
54
+ throw new SignInError('The code ran out: sign in again');
55
+ }
56
+ const sleep = typing.next - Date.now();
57
+ if (Date.now() + Math.max(0, sleep) > until) {
58
+ return undefined;
59
+ }
60
+ if (sleep > 0) {
61
+ await new Promise(resolve => setTimeout(resolve, sleep));
62
+ continue;
63
+ }
64
+ typing.next = Date.now() + typing.interval;
65
+ let answer;
66
+ try {
67
+ answer = await typing.provider.poll(typing.deviceCode);
68
+ }
69
+ catch (failure) {
70
+ // Refused, or the code is no good: over. The network failing is not, and is asked again.
71
+ if (failure instanceof SignInError) {
72
+ this.typing.delete(state);
73
+ }
74
+ throw failure;
75
+ }
76
+ if (answer === 'slowDown') {
77
+ typing.interval += 5000;
78
+ typing.next = Date.now() + typing.interval;
79
+ }
80
+ else if (answer !== 'pending') {
81
+ typing.account = this.of(answer);
82
+ }
83
+ }
84
+ return typing.account;
85
+ }
86
+ /** GitHub by a code, when ta serve has no GitHub of its own. */
87
+ device() {
88
+ const device = this.flow.device;
89
+ return device && !this.flow.providers.some(one => one.id === device.id) ? device : undefined;
90
+ }
91
+ async startTyping(device) {
92
+ const now = Date.now();
93
+ for (const [state, typing] of this.typing) {
94
+ if (now >= typing.expiresAt || this.typing.size >= MAX_TYPING) {
95
+ this.typing.delete(state);
96
+ }
97
+ }
98
+ const code = await device.code();
99
+ const state = randomBytes(18).toString('base64url');
100
+ const interval = Math.max(0, code.interval) * 1000;
101
+ const expiresAt = now + code.expiresIn * 1000;
102
+ this.typing.set(state, { provider: device, deviceCode: code.deviceCode, interval, next: now + interval, expiresAt });
103
+ return { state, device: { code: code.userCode, uri: code.uri, expiresAt } };
104
+ }
105
+ of({ id, name, avatar }) {
26
106
  return { id, ...(name ? { name } : {}), ...(avatar ? { avatar } : {}) };
27
107
  }
28
108
  };
@@ -56,6 +56,7 @@ const RULES = {
56
56
  TaServer: {
57
57
  getServerInfo: anyone,
58
58
  setWorkingDirectory: fixed('settings.manage'),
59
+ restartServer: owner,
59
60
  openSession: (params, lookup) => {
60
61
  var _a;
61
62
  const options = ((_a = params[0]) !== null && _a !== void 0 ? _a : {});
@@ -229,6 +230,10 @@ const RULES = {
229
230
  answer: fixed('models.manage'),
230
231
  cancel: fixed('models.manage'),
231
232
  logout: fixed('models.manage'),
233
+ listCustomProviders: fixed('models.manage'),
234
+ saveCustomProvider: fixed('models.manage'),
235
+ removeCustomProvider: fixed('models.manage'),
236
+ fetchCustomModels: fixed('models.manage'),
232
237
  },
233
238
  TaAccessServer: {
234
239
  getSignInConfig: owner,
@@ -22,6 +22,7 @@ export var WebExtensionUtil;
22
22
  origin: pkg.origin,
23
23
  enabled: (_e = pkg.enabled) !== null && _e !== void 0 ? _e : true,
24
24
  source: pkg.source,
25
+ root: pkg.root,
25
26
  entry,
26
27
  hash: hash(readFileSync(join(pkg.root, entry), 'utf8')),
27
28
  title: text((_a = manifest === null || manifest === void 0 ? void 0 : manifest.pi) === null || _a === void 0 ? void 0 : _a.title),
@@ -1,6 +1,7 @@
1
1
  import type { IncomingMessage, ServerResponse } from 'node:http';
2
2
  import { type ExecEnvironment, ExecEnvironmentFactory, type FileStat } from '@celljs/ta-exec';
3
3
  import { type Context, Middleware } from '@celljs/web/lib/node';
4
+ import { type ThumbnailBox } from './png-thumbnail.js';
4
5
  import { WorkspaceFiles } from './workspace-protocol.js';
5
6
  interface ServedDirectory {
6
7
  root: string;
@@ -24,6 +25,11 @@ export declare namespace WorkspaceFilesUtil {
24
25
  start: number;
25
26
  end: number;
26
27
  } | false | undefined;
28
+ /**
29
+ * The box of `?w=<px>&h=<px>&fit=cover`, which asks for a smaller picture, as the page shows one it has not
30
+ * enlarged (contain without `fit`); undefined for a URL without both sides, or sides out of bounds.
31
+ */
32
+ function thumbnail(url: string | undefined): ThumbnailBox | undefined;
27
33
  function etag(stat: FileStat): string;
28
34
  }
29
35
  /**
@@ -45,9 +51,26 @@ export declare class DefaultWorkspaceFiles implements WorkspaceFiles, Middleware
45
51
  */
46
52
  protected readonly directories: Map<string, ServedDirectory>;
47
53
  protected readonly ids: Map<string, string>;
54
+ /** Smaller pictures made, by file, version and box, the last used last; `null` for one sent as it is. */
55
+ protected readonly thumbnails: Map<string, {
56
+ bytes: Uint8Array;
57
+ type: string;
58
+ } | null>;
59
+ protected thumbnailBytes: number;
60
+ /** Made one at a time: each takes the event loop in turns, and many at once would hold many large pictures. */
61
+ protected making: Promise<unknown>;
48
62
  url(cwd: string, path: string): string;
49
63
  handle(ctx: Context, next: () => Promise<void>): Promise<void>;
50
64
  protected send(request: IncomingMessage, response: ServerResponse, directory: ServedDirectory, path: string): Promise<void>;
65
+ /**
66
+ * A smaller picture of a PNG for `box` (PngThumbnail), with an ETag of its own; false when the picture itself is
67
+ * to be sent (not much larger than the box, or a PNG it does not read).
68
+ */
69
+ protected sendThumbnail(request: IncomingMessage, response: ServerResponse, env: ExecEnvironment, absolute: string, etag: string, box: ThumbnailBox): Promise<boolean>;
70
+ protected keepThumbnail(key: string, made: {
71
+ bytes: Uint8Array;
72
+ type: string;
73
+ } | null): void;
51
74
  /** The file at `path` of `root`, or the `index.html` of the directory there. */
52
75
  protected find(env: ExecEnvironment, root: string, path: string): Promise<{
53
76
  absolute: string;
@@ -14,6 +14,7 @@ import { Autowired, Component, Value } from '@celljs/core';
14
14
  import { ExecEnvironmentFactory } from '@celljs/ta-exec';
15
15
  import { TA_FILES_PATH } from '@celljs/ta-protocol';
16
16
  import { Middleware } from '@celljs/web/lib/node';
17
+ import { PngThumbnail } from './png-thumbnail.js';
17
18
  import { ACCESS_MIDDLEWARE_PRIORITY, TaAccessUtil } from './ta-access.js';
18
19
  import { WorkspaceFiles } from './workspace-protocol.js';
19
20
  import { WorkspaceUtil } from './workspace-util.js';
@@ -65,6 +66,13 @@ const TYPES = {
65
66
  */
66
67
  const SANDBOX = 'sandbox allow-scripts allow-forms allow-popups allow-modals allow-downloads';
67
68
  const ID_BYTES = 16;
69
+ /** The smallest and largest sides of the box a smaller picture is asked for. */
70
+ const THUMB_MIN = 16;
71
+ const THUMB_MAX = 4096;
72
+ /** Smaller pictures kept, made once for every page that shows them, up to this many bytes. */
73
+ const THUMB_CACHE_BYTES = 32 * 1024 * 1024;
74
+ /** Pictures larger than this are sent as they are, never read whole to make a smaller one. */
75
+ const THUMB_SOURCE_BYTES = 48 * 1024 * 1024;
68
76
  /** Read whole from another machine: a part of a larger file is read with `tail` and `head`. */
69
77
  const REMOTE_WHOLE_BYTES = 8 * 1024 * 1024;
70
78
  export var WorkspaceFilesUtil;
@@ -110,6 +118,25 @@ export var WorkspaceFilesUtil;
110
118
  return start <= end && start < size ? { start, end } : false;
111
119
  }
112
120
  WorkspaceFilesUtil.range = range;
121
+ /**
122
+ * The box of `?w=<px>&h=<px>&fit=cover`, which asks for a smaller picture, as the page shows one it has not
123
+ * enlarged (contain without `fit`); undefined for a URL without both sides, or sides out of bounds.
124
+ */
125
+ function thumbnail(url) {
126
+ const query = (url !== null && url !== void 0 ? url : '').split('#')[0].split('?')[1];
127
+ if (!query) {
128
+ return undefined;
129
+ }
130
+ const params = new URLSearchParams(query);
131
+ const side = (name) => {
132
+ const value = Number(params.get(name));
133
+ return Number.isInteger(value) && value >= THUMB_MIN && value <= THUMB_MAX ? value : undefined;
134
+ };
135
+ const width = side('w');
136
+ const height = side('h');
137
+ return width && height ? { width, height, fit: params.get('fit') === 'cover' ? 'cover' : 'contain' } : undefined;
138
+ }
139
+ WorkspaceFilesUtil.thumbnail = thumbnail;
113
140
  function etag(stat) {
114
141
  return `"${stat.size.toString(36)}-${Math.floor(stat.mtimeMs).toString(36)}"`;
115
142
  }
@@ -133,6 +160,11 @@ let DefaultWorkspaceFiles = class DefaultWorkspaceFiles {
133
160
  */
134
161
  this.directories = new Map();
135
162
  this.ids = new Map();
163
+ /** Smaller pictures made, by file, version and box, the last used last; `null` for one sent as it is. */
164
+ this.thumbnails = new Map();
165
+ this.thumbnailBytes = 0;
166
+ /** Made one at a time: each takes the event loop in turns, and many at once would hold many large pictures. */
167
+ this.making = Promise.resolve();
136
168
  }
137
169
  url(cwd, path) {
138
170
  const absolute = resolve(cwd, path || '.');
@@ -193,6 +225,10 @@ let DefaultWorkspaceFiles = class DefaultWorkspaceFiles {
193
225
  response.end();
194
226
  return;
195
227
  }
228
+ const box = type === 'image/png' && !request.headers.range && stat.size <= THUMB_SOURCE_BYTES ? WorkspaceFilesUtil.thumbnail(request.url) : undefined;
229
+ if (box && (await this.sendThumbnail(request, response, env, absolute, etag, box))) {
230
+ return;
231
+ }
196
232
  const range = WorkspaceFilesUtil.range(request.headers.range, stat.size);
197
233
  if (range === false) {
198
234
  response.setHeader('Content-Range', `bytes */${stat.size}`);
@@ -216,6 +252,56 @@ let DefaultWorkspaceFiles = class DefaultWorkspaceFiles {
216
252
  response.end(await this.read(env, absolute, stat.size, start, end));
217
253
  }
218
254
  }
255
+ /**
256
+ * A smaller picture of a PNG for `box` (PngThumbnail), with an ETag of its own; false when the picture itself is
257
+ * to be sent (not much larger than the box, or a PNG it does not read).
258
+ */
259
+ async sendThumbnail(request, response, env, absolute, etag, box) {
260
+ var _a;
261
+ const own = `${etag.slice(0, -1)}-${box.width}x${box.height}${box.fit === 'cover' ? 'c' : ''}"`;
262
+ // Made from this version of the file before: what the page has is still right.
263
+ if (request.headers['if-none-match'] === own) {
264
+ response.setHeader('ETag', own);
265
+ response.removeHeader('Accept-Ranges');
266
+ response.statusCode = 304;
267
+ response.end();
268
+ return true;
269
+ }
270
+ const key = `${absolute}\0${own}`;
271
+ let made = this.thumbnails.get(key);
272
+ if (made === undefined) {
273
+ const making = this.making.then(async () => PngThumbnail.make(await env.readFile(absolute), box).catch(() => undefined));
274
+ this.making = making.catch(() => undefined);
275
+ made = (_a = (await making.catch(() => undefined))) !== null && _a !== void 0 ? _a : null;
276
+ this.keepThumbnail(key, made);
277
+ }
278
+ else {
279
+ this.thumbnails.delete(key);
280
+ this.thumbnails.set(key, made);
281
+ }
282
+ if (!made) {
283
+ return false;
284
+ }
285
+ response.setHeader('ETag', own);
286
+ response.setHeader('Content-Type', made.type);
287
+ response.removeHeader('Accept-Ranges');
288
+ response.statusCode = 200;
289
+ response.setHeader('Content-Length', made.bytes.length);
290
+ response.end(request.method === 'HEAD' ? undefined : made.bytes);
291
+ return true;
292
+ }
293
+ keepThumbnail(key, made) {
294
+ var _a, _b;
295
+ this.thumbnails.set(key, made);
296
+ this.thumbnailBytes += (_a = made === null || made === void 0 ? void 0 : made.bytes.length) !== null && _a !== void 0 ? _a : 0;
297
+ for (const [old, bytes] of this.thumbnails) {
298
+ if (this.thumbnailBytes <= THUMB_CACHE_BYTES && this.thumbnails.size <= 4096) {
299
+ break;
300
+ }
301
+ this.thumbnails.delete(old);
302
+ this.thumbnailBytes -= (_b = bytes === null || bytes === void 0 ? void 0 : bytes.bytes.length) !== null && _b !== void 0 ? _b : 0;
303
+ }
304
+ }
219
305
  /** The file at `path` of `root`, or the `index.html` of the directory there. */
220
306
  async find(env, root, path) {
221
307
  let absolute;
@@ -1,6 +1,6 @@
1
1
  import { type CodingAgentOptions, ModelRuntimeProvider } from '@celljs/ai-coding-agent';
2
2
  import { type RpcConnection } from '@celljs/rpc/lib/node';
3
- import { type TaAuthEvent, type TaAuthProvider, TaAuthServer, type TaAuthType } from '@celljs/ta-protocol';
3
+ import { type TaAuthEvent, type TaAuthProvider, TaAuthServer, type TaAuthType, type TaCustomProvider, type TaCustomProviderInput } from '@celljs/ta-protocol';
4
4
  import { ExtensionProviders } from './extension-providers';
5
5
  import { TaSessionRegistry } from './host-protocol';
6
6
  type ModelRuntime = import('@earendil-works/pi-coding-agent', { with: { 'resolution-mode': 'import' } }).ModelRuntime;
@@ -26,7 +26,7 @@ declare class Login {
26
26
  }
27
27
  export declare namespace AuthServerUtil {
28
28
  /** The ways to sign in, as pi's `/login` lists them, by name. */
29
- function providers(runtime: ModelRuntime, stored: Set<string>): TaAuthProvider[];
29
+ function providers(runtime: ModelRuntime, stored: Set<string>, custom?: Set<string>): TaAuthProvider[];
30
30
  /** pi's AuthEvent as the protocol has it: plain data, and only what a client shows. */
31
31
  function event(event: AuthEvent): TaAuthEvent;
32
32
  }
@@ -41,12 +41,22 @@ export declare class TaAuthServerImpl implements TaAuthServer {
41
41
  protected readonly extensionProviders: ExtensionProviders;
42
42
  protected readonly codingAgentOptions?: CodingAgentOptions;
43
43
  protected readonly logins: Map<string, Login>;
44
+ /** Writes of models.json, one after another. */
45
+ protected writing: Promise<unknown>;
44
46
  protected readonly watched: WeakSet<RpcConnection>;
45
47
  listProviders(): Promise<TaAuthProvider[]>;
46
48
  login(providerId: string, type: TaAuthType): Promise<string>;
47
49
  answer(loginId: string, promptId: string, value: string): Promise<boolean>;
48
50
  cancel(loginId: string): Promise<void>;
49
51
  logout(providerId: string): Promise<void>;
52
+ listCustomProviders(): Promise<TaCustomProvider[]>;
53
+ saveCustomProvider(input: TaCustomProviderInput): Promise<TaCustomProvider>;
54
+ removeCustomProvider(id: string): Promise<void>;
55
+ fetchCustomModels(input: Pick<TaCustomProviderInput, 'id' | 'api' | 'baseUrl' | 'apiKey' | 'headers'>): Promise<string[]>;
56
+ protected modelsFile(): Promise<string>;
57
+ protected readModels(): Promise<Record<string, unknown>>;
58
+ /** models.json changed by `change`, written whole and only the user may read it: it holds keys. */
59
+ protected writeModels<T>(change: (data: Record<string, unknown>) => [Record<string, unknown>, T]): Promise<T>;
50
60
  protected run(runtime: ModelRuntime, login: Login, providerId: string, type: TaAuthType): Promise<void>;
51
61
  /**
52
62
  * Open sessions that have no model, because none was signed in when they opened, take one of the