pairit 0.3.2 → 0.3.4

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 (3) hide show
  1. package/README.md +30 -0
  2. package/dist/index.js +200 -6
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -13,6 +13,7 @@ A lightweight command line utility for working with Pairit experiment configurat
13
13
  - `media delete` — delete a media object from Cloud Storage
14
14
  - `data export` — export sessions, events, and chat messages for a config as CSV/JSON/JSONL
15
15
  - `admin add-user` / `admin remove-user` / `admin list-users` — manage the manager allowlist (admin role required)
16
+ - `admin activity` — show studies with recent sessions, live group studies first (admin role required)
16
17
 
17
18
  ## Install
18
19
 
@@ -96,6 +97,35 @@ Notes:
96
97
  - Self-removal is blocked.
97
98
  - The rejection page contact is set by `MANAGER_ADMIN_CONTACT_EMAIL` (defaults to `harang@pairium.ai`).
98
99
 
100
+ ## Activity (admin)
101
+
102
+ See what is running before you deploy production. Don't deploy while a group study is live.
103
+
104
+ ```bash
105
+ pairit admin activity # studies with sessions in the last 24 h
106
+ pairit admin activity --since 7d # look further back (30m, 2h, 7d, 1w)
107
+ pairit admin activity --json # the raw report
108
+ pairit admin activity --fail-if-live # exit 2 if a group study is live, for scripts
109
+ pairit --env staging admin activity # staging
110
+ ```
111
+
112
+ ```
113
+ 1 group study is live. Don't deploy production.
114
+ omh-test (owner@example.com): 3 active (2 in a group, 1 solo), 1 waiting in matchmaking
115
+
116
+ STUDY OWNER ACTIVE (GROUP/SOLO) WAITING TODAY TOTAL FLAGS
117
+ ● omh-test owner@example.com 3 (2/1) 1 5 127 group,chat,live-workspace,agents
118
+ survey-a r@example.com 1 (0/1) 0 9 40 html
119
+ ```
120
+
121
+ - **Active**: sessions that have not finished and changed in the last 15 minutes. **Group** sessions have been matched into a group; **solo** ones have not.
122
+ - **Waiting**: active sessions on a page with a `matchmaking` component that have not been matched yet.
123
+ - **Today**: sessions started in the last 24 hours. **Total**: all sessions of the config.
124
+ - **Flags**: `group` (the config has a matchmaking pool or component), then the features it uses: `chat`, `live-workspace`, `html`, `agents`.
125
+ - A group study is **live** when it has any active session. Live group studies come first and are marked `●`.
126
+
127
+ `scripts/deploy.sh production` runs `admin activity --fail-if-live` and stops if a group study is live. The manager endpoint is `GET /admin/activity` (optional `since`, an ISO date).
128
+
99
129
  ## Per-experiment LLM credentials
100
130
 
101
131
  If your config uses AI agents, attach provider credentials when uploading:
package/dist/index.js CHANGED
@@ -9230,7 +9230,7 @@ var fallbackAttemptSymbol, __dirname2, localXdgOpenPath, platform, arch, tryEach
9230
9230
  "microsoft-edge.desktop": "edge",
9231
9231
  "com.apple.safari": "safari"
9232
9232
  };
9233
- const flags = {
9233
+ const flags2 = {
9234
9234
  chrome: "--incognito",
9235
9235
  brave: "--incognito",
9236
9236
  firefox: "--private-window",
@@ -9250,7 +9250,7 @@ var fallbackAttemptSymbol, __dirname2, localXdgOpenPath, platform, arch, tryEach
9250
9250
  if (browserName === "safari") {
9251
9251
  throw new Error("Safari doesn't support opening in private mode via command line");
9252
9252
  }
9253
- appArguments.push(flags[browserName]);
9253
+ appArguments.push(flags2[browserName]);
9254
9254
  }
9255
9255
  return baseOpen({
9256
9256
  ...options,
@@ -9480,6 +9480,98 @@ var {
9480
9480
  // src/index.ts
9481
9481
  var import_yaml = __toESM(require_dist(), 1);
9482
9482
 
9483
+ // src/activity.ts
9484
+ var UNIT_MS = {
9485
+ m: 60 * 1000,
9486
+ h: 60 * 60 * 1000,
9487
+ d: 24 * 60 * 60 * 1000,
9488
+ w: 7 * 24 * 60 * 60 * 1000
9489
+ };
9490
+ function parseDuration(value) {
9491
+ const match = /^(\d+)\s*([mhdw])$/.exec(value.trim());
9492
+ if (!match || Number(match[1]) <= 0) {
9493
+ throw new Error(`Invalid duration "${value}". Use a number and a unit: 30m, 2h, 7d, 1w.`);
9494
+ }
9495
+ return Number(match[1]) * UNIT_MS[match[2]];
9496
+ }
9497
+ function isLive(entry) {
9498
+ return entry.isGroupStudy && entry.activeNow.total > 0;
9499
+ }
9500
+ function owner(entry) {
9501
+ return entry.ownerEmail ?? entry.ownerId ?? "-";
9502
+ }
9503
+ function flags(entry) {
9504
+ const list = [];
9505
+ if (entry.isGroupStudy)
9506
+ list.push("group");
9507
+ if (entry.features.chat)
9508
+ list.push("chat");
9509
+ if (entry.features.liveWorkspace)
9510
+ list.push("live-workspace");
9511
+ if (entry.features.html)
9512
+ list.push("html");
9513
+ if (entry.features.agents)
9514
+ list.push("agents");
9515
+ return list.join(",") || "-";
9516
+ }
9517
+ function describeLiveStudy(entry) {
9518
+ const { total, inGroup, solo } = entry.activeNow;
9519
+ return `${entry.configId} (${owner(entry)}): ${total} active (${inGroup} in a group, ${solo} solo), ${entry.waitingInMatchmaking} waiting in matchmaking`;
9520
+ }
9521
+ function formatActivity(report, options = {}) {
9522
+ const paint = (code, text) => options.color ? `\x1B[${code}m${text}\x1B[0m` : text;
9523
+ const lines = [];
9524
+ const live = report.configs.filter(isLive);
9525
+ if (live.length > 0) {
9526
+ lines.push(paint("1;31", `${live.length} group ${live.length === 1 ? "study is" : "studies are"} live. Don't deploy production.`));
9527
+ for (const entry of live)
9528
+ lines.push(` ${describeLiveStudy(entry)}`);
9529
+ } else {
9530
+ lines.push("No group study is live.");
9531
+ }
9532
+ lines.push("");
9533
+ if (report.configs.length === 0) {
9534
+ lines.push(`No sessions since ${report.since}.`);
9535
+ return lines.join(`
9536
+ `);
9537
+ }
9538
+ const rows = [
9539
+ ...live,
9540
+ ...report.configs.filter((entry) => !isLive(entry))
9541
+ ].map((entry) => ({
9542
+ live: isLive(entry),
9543
+ cells: [
9544
+ entry.configId,
9545
+ owner(entry),
9546
+ `${entry.activeNow.total} (${entry.activeNow.inGroup}/${entry.activeNow.solo})`,
9547
+ String(entry.waitingInMatchmaking),
9548
+ String(entry.startedToday),
9549
+ String(entry.totalSessions),
9550
+ flags(entry)
9551
+ ]
9552
+ }));
9553
+ const header = [
9554
+ "STUDY",
9555
+ "OWNER",
9556
+ "ACTIVE (GROUP/SOLO)",
9557
+ "WAITING",
9558
+ "TODAY",
9559
+ "TOTAL",
9560
+ "FLAGS"
9561
+ ];
9562
+ const widths = header.map((title, i) => Math.max(title.length, ...rows.map((row) => row.cells[i].length)));
9563
+ const join = (cells) => cells.map((cell, i) => i === cells.length - 1 ? cell : cell.padEnd(widths[i])).join(" ");
9564
+ lines.push(` ${join(header)}`);
9565
+ for (const row of rows) {
9566
+ const text = join(row.cells);
9567
+ lines.push(row.live ? paint("1;31", `● ${text}`) : ` ${text}`);
9568
+ }
9569
+ lines.push("");
9570
+ lines.push(`Since ${report.since}. Active: not finished and changed in the last ${report.activeWindowMinutes} min. Today: started in the last 24 h.`);
9571
+ return lines.join(`
9572
+ `);
9573
+ }
9574
+
9483
9575
  // src/auth.ts
9484
9576
  import { mkdir, readFile, writeFile } from "node:fs/promises";
9485
9577
  import { homedir } from "node:os";
@@ -9806,6 +9898,71 @@ async function attachHtmlToCompiledConfig(configPath, compiled) {
9806
9898
  }
9807
9899
  return sources;
9808
9900
  }
9901
+ function listWorkspaceComponents(config) {
9902
+ const pages = config.pages;
9903
+ const pageList = Array.isArray(pages) ? pages.filter(isRecord) : isRecord(pages) ? Object.values(pages).filter(isRecord) : [];
9904
+ const result = [];
9905
+ for (const page of pageList) {
9906
+ if (!Array.isArray(page.components))
9907
+ continue;
9908
+ for (const comp of page.components) {
9909
+ if (!isRecord(comp) || comp.type !== "live-workspace")
9910
+ continue;
9911
+ const props = isRecord(comp.props) ? comp.props : {};
9912
+ const id = typeof comp.id === "string" ? comp.id : "live-workspace";
9913
+ result.push({ id, props });
9914
+ }
9915
+ }
9916
+ return result;
9917
+ }
9918
+ async function resolveWorkspaceSchema(schema, componentId, configDir) {
9919
+ if (typeof schema !== "string" || !schema.trim().endsWith(".json")) {
9920
+ throw new Error(`live-workspace ${componentId}: schema must be a .json file`);
9921
+ }
9922
+ const absolutePath = path2.resolve(configDir, schema.trim());
9923
+ const rel = path2.relative(configDir, absolutePath);
9924
+ if (rel.startsWith("..") || path2.isAbsolute(rel)) {
9925
+ throw new Error(`live-workspace ${componentId}: schema must stay inside the config directory`);
9926
+ }
9927
+ try {
9928
+ JSON.parse(await readFile2(absolutePath, "utf8"));
9929
+ } catch (error) {
9930
+ throw new Error(`live-workspace ${componentId}: can't read schema ${schema}: ${error.message}`);
9931
+ }
9932
+ return absolutePath;
9933
+ }
9934
+ async function inspectWorkspaceFiles(configPath, config) {
9935
+ const configDir = await resolveConfigDir(configPath);
9936
+ const errors = [];
9937
+ for (const comp of listWorkspaceComponents(config)) {
9938
+ try {
9939
+ if (comp.props.renderer !== undefined) {
9940
+ await resolveHtmlSource(comp.props.renderer, comp.id, configDir);
9941
+ }
9942
+ if (comp.props.schema !== undefined) {
9943
+ await resolveWorkspaceSchema(comp.props.schema, comp.id, configDir);
9944
+ }
9945
+ } catch (error) {
9946
+ errors.push(error instanceof Error ? error.message : String(error));
9947
+ }
9948
+ }
9949
+ if (errors.length)
9950
+ throw new Error(errors.join(`
9951
+ `));
9952
+ }
9953
+ async function attachWorkspaceFilesToCompiledConfig(configPath, compiled) {
9954
+ const configDir = await resolveConfigDir(configPath);
9955
+ for (const comp of listWorkspaceComponents(compiled)) {
9956
+ if (comp.props.renderer !== undefined) {
9957
+ const resolved = await resolveHtmlSource(comp.props.renderer, comp.id, configDir);
9958
+ comp.props.rendererHtml = await readFile2(resolved.absolutePath, "utf8");
9959
+ }
9960
+ if (comp.props.schema !== undefined) {
9961
+ const schemaPath = await resolveWorkspaceSchema(comp.props.schema, comp.id, configDir);
9962
+ comp.props.schema = JSON.parse(await readFile2(schemaPath, "utf8"));
9963
+ }
9964
+ }
9965
+ }
9809
9966
 
9810
9967
  // src/randomize-lint.ts
9811
9968
  function lintRandomization(config) {
@@ -9865,7 +10022,7 @@ function singleGroupSize(config) {
9865
10022
 
9866
10023
  // src/index.ts
9867
10024
  var program2 = new Command;
9868
- program2.name("pairit").description("CLI for Pairit experiment configs").version("0.3.2").option("--env <name>", "Target environment: staging or production", (value) => {
10025
+ program2.name("pairit").description("CLI for Pairit experiment configs").version("0.3.4").option("--env <name>", "Target environment: staging or production", (value) => {
9869
10026
  try {
9870
10027
  return parseEnvName(value);
9871
10028
  } catch (error) {
@@ -10074,7 +10231,7 @@ dataCommand.command("export").argument("<configId>", "Config ID to export data f
10074
10231
  reportCliError("Export failed", error);
10075
10232
  }
10076
10233
  });
10077
- var adminCommand = program2.command("admin").description("Manage manager allowlist (admin only)");
10234
+ var adminCommand = program2.command("admin").description("Manage the manager allowlist and see activity (admin only)");
10078
10235
  adminCommand.command("add-user").argument("<email>", "Email to allow").option("--admin", "Grant admin privileges").description("Add a user to the manager allowlist").action(async (email, options) => {
10079
10236
  try {
10080
10237
  const response = await callFunctions("/admin/users", {
@@ -10125,6 +10282,32 @@ adminCommand.command("list-users").description("List users on the manager allowl
10125
10282
  reportCliError("List users failed", error);
10126
10283
  }
10127
10284
  });
10285
+ adminCommand.command("activity").description("Show studies with recent sessions, live group studies first (check before deploying production)").option("--since <duration>", "How far back to look, e.g. 2h, 7d", (value) => {
10286
+ try {
10287
+ return parseDuration(value);
10288
+ } catch (error) {
10289
+ throw new InvalidArgumentError(error.message);
10290
+ }
10291
+ }).option("--json", "Print the raw report as JSON").option("--fail-if-live", "Exit with code 2 if any group study has active participants").action(async (options) => {
10292
+ try {
10293
+ const query = options.since ? `?since=${encodeURIComponent(new Date(Date.now() - options.since).toISOString())}` : "";
10294
+ const report = await callFunctions(`/admin/activity${query}`, {
10295
+ method: "GET"
10296
+ });
10297
+ if (options.json) {
10298
+ console.log(JSON.stringify(report, null, 2));
10299
+ } else {
10300
+ console.log(formatActivity(report, {
10301
+ color: Boolean(process11.stdout.isTTY) && !process11.env.NO_COLOR
10302
+ }));
10303
+ }
10304
+ if (options.failIfLive && report.liveGroupStudies.length > 0) {
10305
+ process11.exitCode = 2;
10306
+ }
10307
+ } catch (error) {
10308
+ reportCliError("Activity failed", error);
10309
+ }
10310
+ });
10128
10311
  program2.parseAsync(process11.argv).catch((err) => {
10129
10312
  console.error(err);
10130
10313
  process11.exit(1);
@@ -10161,6 +10344,7 @@ async function lintConfig(configPath) {
10161
10344
  if (errors.length) {
10162
10345
  throw new Error(errors.join(", "));
10163
10346
  }
10347
+ await inspectWorkspaceFiles(configPath, config);
10164
10348
  return inspectHtmlSources(configPath, config);
10165
10349
  }
10166
10350
  async function compileConfig(configPath) {
@@ -10229,6 +10413,7 @@ async function buildUploadPayload(configPath, options) {
10229
10413
  const compiledContent = await readFile3(compiledPath, "utf8");
10230
10414
  const parsed = JSON.parse(compiledContent);
10231
10415
  const attachments = await attachHtmlToCompiledConfig(configPath, parsed);
10416
+ await attachWorkspaceFilesToCompiledConfig(configPath, parsed);
10232
10417
  const hashBuffer = createHash("sha256").update(JSON.stringify(parsed)).digest();
10233
10418
  const checksum = hashBuffer.toString("hex");
10234
10419
  const explicitName = options.name ?? sourceConfig.name;
@@ -10418,6 +10603,7 @@ async function exportData(configId, options) {
10418
10603
  await fetchAndWriteExport(`/data/${cfg}/groups`, path3.join(outDir, `${configId}-groups`), (r) => r.groups ?? [], format, (group) => group, "groups");
10419
10604
  await fetchAndWriteExport(`/data/${cfg}/survey-responses`, path3.join(outDir, `${configId}-survey-responses`), (r) => r.surveyResponses ?? [], format, flattenSurveyResponse, "survey responses");
10420
10605
  await fetchAndWriteExport(`/data/${cfg}/workspace-documents`, path3.join(outDir, `${configId}-workspace-documents`), (r) => r.workspaceDocuments ?? [], format, flattenWorkspaceDocument, "workspace documents");
10606
+ await fetchAndWriteExport(`/data/${cfg}/workspace-updates`, path3.join(outDir, `${configId}-workspace-updates`), (r) => r.workspaceUpdates ?? [], format, (update) => update, "workspace updates");
10421
10607
  console.log(`
10422
10608
  Files written to: ${outDir}`);
10423
10609
  }
@@ -10472,13 +10658,21 @@ function flattenSurveyResponse(response) {
10472
10658
  return flattened;
10473
10659
  }
10474
10660
  function flattenWorkspaceDocument(doc) {
10475
- const { fields, ...rest } = doc;
10476
- const flattened = { ...rest };
10661
+ const { fields, authorship, fieldAuthors, ...rest } = doc;
10662
+ const flattened = {
10663
+ ...rest,
10664
+ authorship: serializeValue(authorship)
10665
+ };
10477
10666
  if (fields && typeof fields === "object") {
10478
10667
  for (const [key, value] of Object.entries(fields)) {
10479
10668
  flattened[`fields.${key}`] = serializeValue(value);
10480
10669
  }
10481
10670
  }
10671
+ if (fieldAuthors && typeof fieldAuthors === "object") {
10672
+ for (const [key, origin] of Object.entries(fieldAuthors)) {
10673
+ flattened[`fieldAuthors.${key}`] = origin;
10674
+ }
10675
+ }
10482
10676
  return flattened;
10483
10677
  }
10484
10678
  function serializeValue(value) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pairit",
3
- "version": "0.3.2",
3
+ "version": "0.3.4",
4
4
  "description": "CLI for the Pairit behavioral science experiment platform",
5
5
  "type": "module",
6
6
  "bin": {