Compare commits

...

92 Commits

Author SHA1 Message Date
Jeff Carr f5b513fa05 buttons for different stuff 2025-09-03 01:19:37 -05:00
Jeff Carr 785591ab4c dumps out the gemini struct enough for now 2025-09-02 18:36:59 -05:00
Jeff Carr 61179d6aae make a "books" window 2025-09-02 17:47:30 -05:00
Jeff Carr 589d50d950 convert is working okay 2025-09-02 15:18:27 -05:00
Jeff Carr 81343b3b66 remove files if it seems close enough 2025-09-02 01:21:24 -05:00
Jeff Carr db079664c9 preliminary import working 2025-09-01 22:19:33 -05:00
Jeff Carr 8220d1817c working on processing JSON files 2025-09-01 20:14:28 -05:00
Jeff Carr 26d674c800 initial table dumps to STDOUT 2025-09-01 18:57:50 -05:00
Jeff Carr 5dadf3b5ef add a GUI 2025-09-01 13:32:25 -05:00
Jeff Carr cdc4155ef1 ignore json files 2025-09-01 12:38:29 -05:00
Jeff Carr 3a1e76e65e gemini-cli is stupid 2025-09-01 12:23:18 -05:00
Jeff Carr c84460eb65 it builds 2025-09-01 03:37:10 -05:00
Jeff Carr c65619154e sub in the functions 2025-09-01 01:55:06 -05:00
Jeff Carr c63a746d0b isolate this function 2025-09-01 01:41:03 -05:00
Jeff Carr c110250dc2 something? 2025-09-01 00:35:05 -05:00
Jeff Carr 4a800a7cfd attempts to submit data to the Gemini API 2025-09-01 00:29:48 -05:00
Castor Regex eba85c6b97 feat: dump last chat entry 2025-08-31 22:34:53 -05:00
Castor Regex 710693b18a feat: add dumpchat function 2025-08-31 22:31:11 -05:00
Castor Regex 8c8fccc650 feat: print last playback UUID 2025-08-31 22:26:49 -05:00
Jeff Carr 535cb98744 looking good. adds the json file okay 2025-08-30 19:08:41 -05:00
Jeff Carr 6ce2991074 more crap 2025-08-30 18:48:44 -05:00
Jeff Carr 96843095f5 minor 2025-08-30 18:14:47 -05:00
Jeff Carr fbbed0475b parse stuff 2025-08-30 18:07:41 -05:00
Jeff Carr 512ebf5be6 attempt to marshal JSON file to protobuf 2025-08-30 16:54:54 -05:00
Jeff Carr 6888512b3b minor cleanups 2025-08-30 16:17:01 -05:00
Jeff Carr b750fb9252 GEMINI workflow rules 2025-08-30 15:48:22 -05:00
Jeff Carr bbb12d79e2 more code cleanups 2025-08-30 15:24:54 -05:00
Jeff Carr c7896e47f9 code cleanup of early drafts of code from Gemini AI 2025-08-30 15:15:43 -05:00
Jeff Carr 7f8f5e3b9b basic JSON parsing into genai struc 2025-08-30 14:42:57 -05:00
Jeff Carr c971bfddf7 minor 2025-08-28 11:30:13 -05:00
Jeff Carr 5fff0c4d70 testing 2025-08-26 11:42:51 -05:00
Jeff Carr a20e4e0533 work in progress 2025-08-26 11:12:23 -05:00
Castor Regex 25e483898f feat(regex): print regex.log and sleep after ready 2025-08-25 17:24:00 -05:00
Castor Regex 3db9d84b63 fix(regex): delete ready file after detection 2025-08-25 11:57:20 -05:00
Castor Regex 4f215037a1 feat(editor): wait for ready file and rename to doEditor.go 2025-08-25 11:49:30 -05:00
Jeff Carr f5b923f180 can now send questions to gemini-cli from regex 2025-08-25 10:58:47 -05:00
Jeff Carr a813b2e206 test 2025-08-25 10:48:59 -05:00
Castor Regex 0b2ec9ce15 fix: correct build errors and clean up code 2025-08-25 10:15:39 -05:00
Jeff Carr c39a2f31e6 stuff 2025-08-24 19:34:44 -05:00
Castor Regex a9b7fca08d feat(chat): add --get-next-auto-topic flag 2025-08-24 13:23:12 -05:00
Castor Regex 82eba977cd fix(count-auto): load chats before counting 2025-08-24 13:14:48 -05:00
Castor Regex 9c7d2a9c9e fix(count-auto): suppress debug output 2025-08-24 13:11:19 -05:00
Castor Regex b03889101d feat(chat): add --new-chat and --count-auto flags 2025-08-24 13:07:43 -05:00
Castor Gemini 1a6b367144 feat(stats): add --stats flag to save session stats 2025-08-24 09:01:34 -05:00
Castor Gemini cd170de677 feat(playback): Improve formatting of long playback 2025-08-24 08:39:59 -05:00
Castor Gemini 357c20027f Refactor: Rename gemini to regex throughout the codebase 2025-08-24 01:21:01 -05:00
Castor Gemini 0a28d985b8 Fix: Update Makefile to build regex binary 2025-08-24 01:08:38 -05:00
Castor Gemini 40243de35b feat(gemini): add file import capability
This commit introduces the `doImport` function, which allows importing
the content of a file directly into the "auto" chat session.

The imported content is added as a `ChatEntry` from GEMINI, structured
as a `ToolCall` with the name "Shell" and the file content as the input.
This allows external command outputs to be seamlessly integrated into
the chat history for context.
2025-08-22 11:47:00 -05:00
Jeff Carr 7646310dd4 show 'auto' by default 2025-08-22 11:22:52 -05:00
Jeff Carr cf812da1d3 add doInput() 2025-08-22 10:43:52 -05:00
Castor Gemini 5db2567e60 feat(gemini): add timestamp to auto chat entries 2025-08-22 10:16:00 -05:00
Castor Gemini 3f6a796181 fix(gemini): set author to GEMINI in doOutput 2025-08-22 10:13:55 -05:00
Castor Gemini 48ba121435 feat(gemini): update "auto" chat on --output 2025-08-22 10:12:05 -05:00
Jeff Carr e6737ba635 fix log output 2025-08-22 08:55:59 -05:00
Castor Gemini 249c2a97b8 Log doOutput to /tmp/gemini-output.log 2025-08-22 06:18:18 -05:00
Jeff Carr fbc5ebe4ce wtf. this should work 2025-08-22 06:12:47 -05:00
Castor Gemini d9e7420b31 fix(playback): Improve formatting of code snippets
- Refactor the 'printCodeSnippet' function to draw a complete,
  correctly padded box around the code.
- Each line is now padded with spaces to ensure the right border
  aligns perfectly at the terminal width.
2025-08-22 05:47:02 -05:00
Castor Gemini a08314efb8 fix(playback): Correct Printf formatting for right-alignment
- Fix a bug where the format string for the right-aligned prefix
  was being printed literally instead of being evaluated.
- The user message prefix now displays the timestamp and author
  correctly.
2025-08-22 05:44:42 -05:00
Castor Gemini 9b71be25d0 fix(playback): Correct right-alignment of user messages
- Refactor the 'printRightAligned' function to print the author
  prefix line *before* the content.
- This fixes a bug where the prefix was incorrectly appearing after
  the message body.
2025-08-22 05:40:02 -05:00
Castor Gemini 7b65b5b237 fix(playback): Add spacing before code snippets 2025-08-22 05:37:49 -05:00
Castor Gemini e26d8dd9b3 feat(playback): Add right-alignment for user messages
- Refactor the 'printContent' function to align user messages to
  the right side of the terminal.
- Gemini messages remain left-aligned.
- This provides a clearer visual distinction in the conversation flow.
2025-08-22 05:35:20 -05:00
Castor Gemini 684503fd07 fix(playback): Correct content indentation logic
- Refactor the word-wrapping algorithm in 'printContent' to
  ensure every line of conversational text is correctly
  prepended with a tab character.
- This fixes the issue where only the first line of a wrapped
  paragraph was being indented.
2025-08-22 05:31:35 -05:00
Castor Gemini b8b64da118 fix(playback): Improve content word wrapping
- Refactor the 'printContent' function to provide a cleaner layout.
- The author and timestamp prefix now appear on their own line.
- All subsequent lines of content are indented with a standard tab
  and wrapped correctly to the terminal width.
2025-08-22 05:28:06 -05:00
Castor Gemini 69395ccb0a fix(playback): Implement word wrapping for content
- Add a new 'printContent' function to handle word wrapping for the
  main conversational text in the detailed playback view.
- This ensures that long lines of text are correctly wrapped to the
  terminal width, improving readability.
2025-08-22 05:21:25 -05:00
Castor Gemini 02dd197abc refactor(ui): Adjust playback format width to 100 characters 2025-08-22 05:18:09 -05:00
Jeff Carr 1fb23427bd jesus 2025-08-22 05:00:08 -05:00
Jeff Carr 24f9157d50 blah 2025-08-22 04:35:14 -05:00
Castor Gemini 0e6bc36984 feat(playback): Implement listEntries for chat summary
- Implement a new 'listEntries' function that provides a one-line
  summary for each entry within a chat topic.
- The 'showChat' function (triggered by 'playback --uuid') now
  calls this new summary view.
2025-08-22 04:30:02 -05:00
Jeff Carr d0c27606a3 Revert "feat(playback): Implement listEntries for chat summary"
This reverts commit af9bc2db8c.
2025-08-22 04:29:10 -05:00
Castor Gemini af9bc2db8c feat(playback): Implement listEntries for chat summary
- Implement a new 'listEntries' function that provides a one-line
  summary for each entry within a chat topic.
- The 'showChat' function (triggered by 'playback --uuid') now
  calls this new summary view instead of the full rich format.
2025-08-22 04:26:25 -05:00
Jeff Carr eceb945b9c something new 2025-08-22 04:23:28 -05:00
Castor Gemini 126495ff38 fix(playback): Correctly handle UUID argument
- Update the main command loop to correctly parse and pass the
  '--uuid' flag to the showChat function.
- This fixes the 'invalid subcommand' error and makes the detailed
  playback view fully functional.
2025-08-22 04:08:54 -05:00
Jeff Carr 76ef21fc66 new logging 2025-08-22 04:00:41 -05:00
Castor Gemini 8f9726c6e4 refactor(add): Create dedicated addFile function
- Move all file reading and content-inlining logic into a new
  'addFile' function in its own 'add.go' file.
- The main function now calls this to parse a log file and then
  appends the returned chats to the main session.
- This improves separation of concerns and makes the main loop cleaner.
2025-08-22 03:45:34 -05:00
Castor Gemini 73bc0f73aa fix(playback): Make playback independent of the filesystem
- Refactor the prettyFormat.go functions to render all content
  directly from the 'Content' fields of the protobuf messages.
- Remove all 'os.ReadFile' calls from the formatting logic.
- This ensures the 'playback' command is self-contained and works
  correctly on saved protobuf data where the original content files
  are no longer available.
2025-08-22 03:36:54 -05:00
Jeff Carr 5b7e2daf65 stuff 2025-08-22 03:34:45 -05:00
Castor Gemini f6e881b064 refactor(playback): Move formatting logic to prettyFormat.go
- Create a new prettyFormat.go file to contain all the detailed
  log formatting and printing logic.
- Simplify doPlayback.go to handle the summary view and call out
  to the new prettyFormatChat function for detailed views.
- This separation of concerns makes the code cleaner and fixes
  compilation errors related to redeclared functions.
2025-08-22 03:26:39 -05:00
Jeff Carr dc2b0eeb06 something 2025-08-22 03:22:52 -05:00
Jeff Carr baba0da261 Revert "feat(playback): Implement detailed view for showChat"
This reverts commit df4e63ea75.
2025-08-22 03:20:11 -05:00
Castor Gemini df4e63ea75 feat(playback): Implement detailed view for showChat
- Integrate the rich formatting logic into the 'showChat' function.
- When 'playback' is called with a UUID, it now prints a full,
  detailed transcript of that specific chat topic, including
  content from external files, tool calls, and code snippets.
2025-08-22 03:19:10 -05:00
Jeff Carr e69177bc53 find uuid 2025-08-22 03:15:41 -05:00
Jeff Carr 05105e6fd1 Revert "feat(playback): Create new, correct playback summary function"
This reverts commit 6770c0ac1e.
2025-08-22 03:09:24 -05:00
Castor Gemini 6770c0ac1e feat(playback): Create new, correct playback summary function
- Create a new, self-contained doPlayback.go that correctly
  implements the summary view.
- This function is designed to be called with an optional filename.
- Note: This leaves main.go in a broken state, requiring the user
  to update the call site to this new function.
2025-08-22 03:05:26 -05:00
Castor Gemini ba1e58f797 feat(playback): Add UUID to summary view 2025-08-22 03:00:47 -05:00
Castor Gemini bffc301568 refactor(gemini): Adapt app to new protobuf structure
- Update main.go and doPlayback.go to be compatible with the
  refactored 'Chat -> Entries' protobuf message format.
- Remove the now-obsolete format_rich_log.go file.
- The application now compiles successfully against the new chatpb library.
2025-08-22 02:51:47 -05:00
Castor Gemini 3d6f228b6e feat(playback): Change playback to a concise summary view
- The 'playback' command now prints a one-line summary for each
  chat topic.
- The summary includes the topic name, the number of entries,
  and the start time of the conversation.
2025-08-22 02:29:39 -05:00
Jeff Carr 043386b95b GPL 2025-08-22 00:50:20 -05:00
Castor Gemini 279c0d0e6c fix: Add diagnostic check for nil chat entries 2025-08-22 00:36:54 -05:00
Jeff Carr 44f860caa0 trying to improve forge 2025-08-21 22:27:16 -05:00
Jeff Carr a10b75d453 make an --add <filename> option 2025-08-21 14:13:42 -05:00
Jeff Carr b221e7a95c add ConfigSave() 2025-08-21 12:30:36 -05:00
Jeff Carr e655b37e60 misc 2025-08-21 10:59:11 -05:00
35 changed files with 2722 additions and 84 deletions

4
.gitignore vendored
View File

@ -3,4 +3,6 @@ go.mod
go.sum
/resources/*.so
/files/*
gemini
regex
/tmp/*
*.json

17
GEMINI.md Normal file
View File

@ -0,0 +1,17 @@
## Gemini Added Memories
- The user and I were analyzing a RISC-V Go panic. The user provided a panic log showing a 'SIGQUIT: quit' signal. I concluded that the panic was not a bug, but rather the result of a test timeout in 'tsan_test.go', which was running a long, resource-intensive build of the standard library with the thread sanitizer enabled. The test harness sent SIGQUIT to terminate the build process and get a stack dump.
- Assume my base directory is `/home/jcarr/go/src`
- The gemini-cli application is located in github.com/google-gemini/gemini-cli and is a Node.js project.
- To test the build of gemini-cli, always run exactly: cd github.com/google-gemini/gemini-cli && make build
- The "regex" application is located in `go.wit.com/apps/regex` and is written in Go
- To build the 'regex' application, I must first change into the `go.wit.com/apps/regex` directory and then run the `make regex` command.
- The "Google Gemini AI GO API" is located in `google.golang.org/genai`.
- I must not search for anything. Instead, I must stop and ask the user for the location of files or information.
- When committing to git, I will use the author name 'Castor Regex' and the email 'regex@wit.com'.
- My git workflow is: 1. `git status`. 2. `git add <files>`. 3. `GIT_AUTHOR_NAME='Castor Regex' GIT_AUTHOR_EMAIL='regex@wit.com' git commit -m '...'`. I will not run `git push`.
- When asked to commit code with git, I should follow the git workflow
- My standard workflow: Upon completing a task and verifying the solution, I will automatically commit the changes. Then follow my git workflow
- My standard git workflow: Upon completing a task and verifying the solution, I will automatically commit the changes following the standard workflow.
- New operational rule: If a fix or modification I make results in an error, I will NOT revert the changes with `git checkout`. I will leave the modified files in their current state for the user to inspect and debug.
- CRITICAL WORKFLOW RULE: After making any code changes and before committing, I MUST always attempt to build the project (e.g., run 'make' or the appropriate build command). I am only allowed to commit changes that compile successfully. If a build fails, I must fix the compilation error before proceeding with the commit. I will not commit broken code.
- WORKFLOW UPDATE: If a build fails and the user subsequently tells me to commit, I will assume the user has fixed the compilation errors. My next step is to re-run the build command to verify. If this verification build succeeds, I will then proceed with committing my original changes. If it still fails, I will report the new error.

674
LICENSE Normal file
View File

@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.

View File

@ -1,47 +1,60 @@
VERSION = $(shell git describe --tags)
BUILDTIME = $(shell date +%Y.%m.%d_%H%M)
default: verbose
default: install
regex clean
vet:
@GO111MODULE=off go vet
@echo this go binary package builds okay
verbose: goimports vet plugin
verbose: goimports vet
GO111MODULE=off go install -v -x \
-ldflags "-X main.VERSION=${VERSION} -X main.BUILDTIME=${BUILDTIME} -X gui.GUIVERSION=${VERSION}"
build: goimports vet plugin
GO111MODULE=off go build -v -x \
build: goimports
GO111MODULE=off go build \
-ldflags "-X main.VERSION=${VERSION} -X main.BUILDTIME=${BUILDTIME} -X gui.GUIVERSION=${VERSION}"
install: goimports vet plugin
install: goimports
GO111MODULE=off go install \
-ldflags "-X main.VERSION=${VERSION} -X main.BUILDTIME=${BUILDTIME} -X gui.GUIVERSION=${VERSION}"
install-raw: goimports vet plugin
regex: goimports
GO111MODULE=off go install \
-ldflags "-X main.VERSION=${VERSION} -X main.BUILDTIME=${BUILDTIME} -X gui.GUIVERSION=${VERSION}"
CUI: install
regex --gui gocui
GTK: clean install
regex --gui andlabs
dumb-build:
go install -v -x \
-ldflags "-X main.VERSION=${VERSION} -X main.BUILDTIME=${BUILDTIME} -X gui.GUIVERSION=${VERSION}"
install-raw: goimports vet
go install \
-ldflags "-X main.VERSION=${VERSION} -X main.BUILDTIME=${BUILDTIME} -X gui.GUIVERSION=${VERSION}"
plugin:
rm -f resources/*.so
# -cp ../../toolkits/gocui/gocui.so resources/
andlabs: clean install
gemini --gui gocui --gui-verbose --gui-file ../../toolkits/andlabs/andlabs.so
gocui: install
gemini --gui gocui --gui-verbose --gui-file ../../toolkits/gocui/gocui.so >/tmp/gemini.log 2>&1
goimports:
reset
goimports -w *.go
@# // to globally reset paths:
@# // gofmt -w -r '"go.wit.com/gui/gadgets" -> "go.wit.com/lib/gadgets"' *.go
clean:
-rm -f gemini go.*
-rm -f regex go.*
go-mod-clean purge
identify-protobuf:
autogenpb --identify ~/.gemini/gemini.pb
autogenpb --identify "~/.regex/regex.pb"
playback:
regex playback
# regex playback --uuid a1b2c3d4-e5f6-4a5b-8c9d-1e2f3a4b5c6d
tmpfiles:
ls -tl /tmp/regex.* |head

44
README.md Normal file
View File

@ -0,0 +1,44 @@
Gemini is the engine. Vertex AI is the entire car.
* Gemini is the name of the powerful, multimodal AI model family itself. It's the "brain" that performs the reasoning, understands text, images, audio, and video, and
generates responses.
* Vertex AI is the comprehensive, enterprise-grade platform on Google Cloud where you can access, deploy, manage, and even customize models like Gemini. It's the
infrastructure, the dashboard, the security features, and the MLOps (Machine Learning Operations) toolkit that surrounds the engine.
Here is a more detailed breakdown:
Gemini AI
* What it is: A family of highly capable large language models (LLMs).
* What it does: It's the core technology that processes information and generates output. It comes in different sizes and capabilities, like Gemini 1.5 Pro, Gemini
1.5 Flash, and Gemini Ultra, each optimized for different tasks (speed, cost, power).
* Key Features:
* Multimodality: Natively understands and reasons across text, code, images, audio, and video.
* Long Context: Can process massive amounts of information at once (e.g., Gemini 1.5 Pro has a 1 million token context window).
* Advanced Reasoning: Capable of complex, multi-step reasoning tasks.
* How you access it: You access Gemini through an API. That API can be part of Vertex AI or part of a simpler platform like Google AI Studio.
Vertex AI
* What it is: A fully-managed Machine Learning (ML) platform on Google Cloud.
* What it does: It provides all the tools and infrastructure needed to build, deploy, and manage ML models in a production environment. It's not just for Gemini; you
can use it for custom models built with TensorFlow or PyTorch, or other foundation models.
* Key Features:
* Model Garden: A central place to discover and use Google's foundation models (like Gemini) and hundreds of open-source models.
* Enterprise Security & Governance: Integrates with Google Cloud's robust security features like IAM (Identity and Access Management), VPC Service Controls, and
data encryption. Your data remains within your cloud environment.
* Data Integration: Seamlessly connects to other Google Cloud services like BigQuery and Cloud Storage, allowing you to use your own data with the models.
* Tuning and Customization: Provides tools to fine-tune foundation models like Gemini on your own data to make them experts in your specific domain.
* MLOps: A full suite of tools for automating, monitoring, and managing the entire ML lifecycle (pipelines, versioning, etc.).
How They Work Together
You don't choose between Vertex AI and Gemini. You choose how you want to use Gemini, and Vertex AI is the professional, enterprise-grade way to do it.
* When you call the Gemini API via Vertex AI, you get all the benefits of the Google Cloud platform: security, data privacy, scalability, and integration with your
other cloud resources. This is the path for building production applications.
* There is another way to access Gemini: Google AI Studio. This is a web-based tool designed for rapid prototyping and experimentation. It's great for developers who
want to quickly try out prompts and build an API key, but it doesn't have the enterprise-level MLOps and governance features of Vertex AI.
Summary Table

62
add.go Normal file
View File

@ -0,0 +1,62 @@
package main
import (
"os"
"path/filepath"
"go.wit.com/lib/protobuf/chatpb"
"go.wit.com/log"
)
// addFile reads a protobuf text file, inlines all external content, and returns
// a self-contained *chatpb.Chats object.
func addFile(filename string) (*chatpb.Chats, error) {
data, err := os.ReadFile(filename)
if err != nil {
return nil, log.Errorf("failed to read file %s: %w", filename, err)
}
logData, err := chatpb.UnmarshalChatsTEXT(data)
if err != nil {
return nil, log.Errorf("failed to unmarshal log file %s: %w", filename, err)
}
log.Info("Successfully parsed log file: %s", filename)
// Get the directory of the log file to resolve relative content paths.
logDir := filepath.Dir(filename)
// Iterate through the structure to inline all external content.
for _, chat := range logData.Chats {
for _, entry := range chat.Entries {
// Inline main content from ContentFile
if contentFile := entry.ContentFile; contentFile != "" {
contentPath := filepath.Join(logDir, contentFile)
contentBytes, err := os.ReadFile(contentPath)
if err != nil {
entry.Content = log.Sprintf("--- ERROR: Could not read content file %s: %v ---", contentPath, err)
} else {
entry.Content = string(contentBytes)
}
}
// Inline snippet content from snippet files
if snippets := entry.Snippets; snippets != nil {
for _, snippet := range snippets {
if snippetFile := snippet.Filename; snippetFile != "" {
snippetPath := filepath.Join(logDir, snippetFile)
contentBytes, err := os.ReadFile(snippetPath)
if err != nil {
snippet.Content = log.Sprintf("--- ERROR: Could not read snippet file %s: %v ---", snippetPath, err)
} else {
snippet.Content = string(contentBytes)
}
}
}
}
}
}
log.Info("Successfully inlined all external content.")
return logData, nil
}

13
addResponse.go Normal file
View File

@ -0,0 +1,13 @@
package main
import (
"go.wit.com/log"
"google.golang.org/genai"
)
func addResponse(resp *genai.GenerateContentResponse) {
pb := convertToPB(resp)
log.Info(resp)
me.lastChat.AppendEntry(pb)
me.chats.ConfigSave()
}

65
apiExampleCode.go Normal file
View File

@ -0,0 +1,65 @@
package main
// this is just example code the GO API's wrapper for handling statelessness
// it doesn't really compile and is just junk Gemini AI sent back but I saved it here anyway
/*
func statelessnessExample() {
ctx := context.Background()
// Get the API key from an environment variable
apiKey := os.Getenv("GEMINI_API_KEY")
if apiKey == "" {
log.Fatal("GEMINI_API_KEY environment variable not set")
}
// Create a new client
client, err := genai.NewClient(ctx, option.WithAPIKey(apiKey))
if err != nil {
log.Fatal(err)
}
defer client.Close()
// Choose the model
model := client.GenerativeModel("gemini-1.5-flash")
// ---- Start a new chat session ----
cs := model.StartChat()
cs.History = []*genai.Content{} // Start with a clean history
// --- First message ---
fmt.Println("User: My brother's name is Paul.")
resp, err := cs.SendMessage(ctx, genai.Text("My brother's name is Paul."))
if err != nil {
log.Fatal(err)
}
printResponse(resp)
// --- Second message ---
// The ChatSession now remembers the previous exchange.
fmt.Println("\nUser: What is my brother's name?")
resp, err = cs.SendMessage(ctx, genai.Text("What is my brother's name?"))
if err != nil {
log.Fatal(err)
}
printResponse(resp)
// You can inspect the history at any time
// fmt.Println("\n--- Full Chat History ---")
// for _, content := range cs.History {
// for _, part := range content.Parts {
// fmt.Printf("Role: %s, Text: %v\n", content.Role, part)
// }
// }
}
// Helper function to print the response
func printResponse(resp *genai.GenerateContentResponse) {
for _, cand := range resp.Candidates {
if cand.Content != nil {
for _, part := range cand.Content.Parts {
fmt.Printf("Gemini: %v\n", part)
}
}
}
}
*/

21
argv.go
View File

@ -10,8 +10,14 @@ package main
var argv args
type args struct {
Uuid string `arg:"--uuid" help:"look at this uuid"`
Topic string `arg:"--topic" help:"set the topic"`
JsonFile string `arg:"--json" help:"import a JSON file from gemini-cli"`
Interact *EmptyCmd `arg:"subcommand:interact" help:"open env EDITOR"`
Playback *PlaybackCmd `arg:"subcommand:playback" help:"dump your prior conversations to the terminal'"`
Add *EmptyCmd `arg:"subcommand:add" help:"add a conversation"`
NewChat *PlaybackCmd `arg:"subcommand:newchat" help:"used by gemini-cli on startup"`
Clean *CleanCmd `arg:"subcommand:clean" help:"cleanup the files in /tmp"`
Stats string `arg:"--stats" help:"add stats to a chat"`
Force bool `arg:"--force" help:"try to strong arm things"`
Verbose bool `arg:"--verbose" help:"show more output"`
Bash bool `arg:"--bash" help:"generate bash completion"`
@ -21,9 +27,16 @@ type args struct {
type EmptyCmd struct {
}
type CleanCmd struct {
Match string `arg:"positional"`
}
type PlaybackCmd struct {
List *EmptyCmd `arg:"subcommand:list" help:"list memories"`
Force bool `arg:"--all" help:"try to strong arm things"`
Last *EmptyCmd `arg:"subcommand:last" help:"dump the last one"`
List *EmptyCmd `arg:"subcommand:list" help:"list memories"`
Long *EmptyCmd `arg:"subcommand:long" help:"show info on each chat"`
Purge *EmptyCmd `arg:"subcommand:purge" help:"verify chat uuids & purge empty chats"`
Submit *EmptyCmd `arg:"subcommand:submit" help:"convert and submit the last entry"`
}
func (args) Version() string {
@ -32,6 +45,6 @@ func (args) Version() string {
func (a args) Description() string {
return `
gemini -- interact with Googles' Gemini AI
regex -- interact with Googles' Gemini AI
`
}

View File

@ -21,16 +21,16 @@ func deleteMatch() {
}
func (args) doBashAuto() {
argv.doBashHelp()
// argv.doBashHelp()
switch argv.BashAuto[0] {
case "playback":
fmt.Println("list --force")
fmt.Println("long --uuid purge last submit")
case "clean":
fmt.Println("user devel master")
fmt.Println("")
default:
if argv.BashAuto[0] == ARGNAME {
// list the subcommands here
fmt.Println("playback add")
fmt.Println("--json interact playback clean")
}
}
os.Exit(0)
@ -51,43 +51,10 @@ func (args) doBashHelp() {
return
}
fmt.Fprintln(os.Stderr, "")
fmt.Fprintln(os.Stderr, "hello world")
fmt.Fprintln(os.Stderr, "something went wrong with the GO args package")
fmt.Fprintln(os.Stderr, "")
}
/*
// complete -F forge --bash forge
func (args) doBash() {
fmt.Println("# add this in your bashrc:")
fmt.Println("")
fmt.Println("# todo: add this to go-arg as a 'hidden' go-arg option --bash")
fmt.Println("#")
fmt.Println("# todo: can this output work/parse with:")
fmt.Println("# complete -C `" + ARGNAME + " --bash` " + ARGNAME)
fmt.Println("")
fmt.Println("_" + ARGNAME + "_complete()")
fmt.Println("{")
fmt.Println(" # sets local to this func vars")
fmt.Println(" local cur prev all")
fmt.Println(" cur=${COMP_WORDS[COMP_CWORD]}")
fmt.Println(" prev=${COMP_WORDS[COMP_CWORD-1]}")
fmt.Println(" all=${COMP_WORDS[@]}")
fmt.Println("")
fmt.Println(" # this is where we generate the go-arg output")
fmt.Println(" GOARGS=$(" + ARGNAME + " --auto-complete $prev \\'$cur\\' $all)")
fmt.Println("")
fmt.Println(" # this compares the command line input from the user")
fmt.Println(" # to whatever strings we output")
fmt.Println(" COMPREPLY=( $(compgen -W \"$GOARGS\" -- $cur) ) # THIS WORKS")
fmt.Println(" return 0")
fmt.Println("}")
fmt.Println("complete -F _" + ARGNAME + "_complete " + ARGNAME)
fmt.Println("")
fmt.Println("# copy and paste the above into your bash shell should work")
os.Exit(0)
}
*/
// complete -F forge --bash forge
func (args) doBash() {
fmt.Println("# add this in your bashrc:")

26
convertToGenai.go Normal file
View File

@ -0,0 +1,26 @@
package main
import (
"go.wit.com/lib/protobuf/chatpb"
"google.golang.org/genai"
)
// convertToGenai transforms the parsed JSON request into the genai.Content format.
func convertToGenai(req *chatpb.GeminiRequest) ([]*genai.Content, error) {
var contents []*genai.Content
for _, c := range req.GetContents() {
var genaiParts []*genai.Part
for _, p := range c.GetParts() {
switch v := p.GetPartType().(type) {
case *chatpb.Part_Text:
part := &genai.Part{Text: v.Text}
genaiParts = append(genaiParts, part)
}
}
contents = append(contents, &genai.Content{
Role: c.GetRole(),
Parts: genaiParts,
})
}
return contents, nil
}

48
convertToPB.go Normal file
View File

@ -0,0 +1,48 @@
package main
import (
"fmt"
"go.wit.com/lib/protobuf/chatpb"
"google.golang.org/genai"
)
func convertToPB(resp *genai.GenerateContentResponse) *chatpb.ChatEntry {
entry := &chatpb.ChatEntry{}
if resp == nil || len(resp.Candidates) == 0 || resp.Candidates[0].Content == nil {
return entry
}
content := resp.Candidates[0].Content
for _, part := range content.Parts {
if part.Text != "" {
entry.Parts = append(entry.Parts, &chatpb.Part{
PartType: &chatpb.Part_Text{Text: part.Text},
})
}
if fc := part.FunctionCall; fc != nil {
fmt.Printf("Gemini API requested to execute command: %s\n", fc.Name)
entry.Parts = append(entry.Parts, &chatpb.Part{
PartType: &chatpb.Part_FunctionCall{
FunctionCall: &chatpb.FunctionCall{
Name: fc.Name,
Args: &chatpb.ArgsInfo{}, // TODO: Properly map args from fc.Args map[string]any
},
},
})
}
if fr := part.FunctionResponse; fr != nil {
// Convert the FunctionResponse to the protobuf equivalent
entry.Parts = append(entry.Parts, &chatpb.Part{
PartType: &chatpb.Part_FunctionResponse{
FunctionResponse: &chatpb.FunctionResponse{
Name: fr.Name,
// TODO: Properly map the response content
},
},
})
}
}
return entry
}

20
debugger.go Normal file
View File

@ -0,0 +1,20 @@
package main
/*
enables GUI options and the debugger in your application
*/
import (
"go.wit.com/lib/debugger"
"go.wit.com/log"
)
func init() {
if debugger.ArgDebug() {
log.Info("cmd line --debugger == true")
go func() {
log.Sleep(2)
debugger.DebugWindow()
}()
}
}

129
doClean.go Normal file
View File

@ -0,0 +1,129 @@
package main
import (
"os"
"path/filepath"
"strings"
"go.wit.com/lib/protobuf/chatpb"
"go.wit.com/log"
"google.golang.org/protobuf/types/known/timestamppb"
)
func doClean() {
log.Info("find all files")
scanTmp()
}
func scanTmp() {
var count int
filepath.WalkDir("/tmp", func(path string, d os.DirEntry, err error) error {
if err != nil {
// Handle possible errors, like permission issues
// fmt.Fprintf(os.Stderr, "error accessing path %q: %v\n", path, err)
// ignore all these problems
return err
}
/*
if d.IsDir() {
// log.Info("path is dir", path)
return nil
}
*/
_, fname := filepath.Split(path)
if !strings.HasPrefix(fname, "regex.") {
return nil
}
if count > 100 {
return log.Errorf("count exceeded")
}
if strings.HasPrefix(fname, "regex.gemini-api-response") {
// log.Info("response file:", fname)
return nil
}
if strings.Contains(fname, "gemini-api-request") {
// log.Info("response file:", fname)
if err := cleanGeminiFile(path); err == nil {
count += 1
return nil
} else {
return nil
}
}
if strings.HasSuffix(fname, ".stats") {
cleanStatsFile(path)
return nil
}
log.Info("check file:", path)
return nil
})
}
func cleanStatsFile(fullname string) {
log.Info("stats file", fullname)
}
func cleanGeminiFile(fullname string) error {
_, fname := filepath.Split(fullname)
if !strings.HasSuffix(fname, ".json") {
return log.Errorf("not really gemini-api-request .json")
}
parts := strings.Split(fname, ".")
if len(parts) == 5 {
if parts[2] != "gemini-api-request" {
return log.Errorf("not really gemini-api-request")
}
}
// log.Info("PARSE FILE:", fullname)
pb, err := parsePB(fullname)
if err != nil {
log.Info("parsePB() %s err %v\n", fullname, err)
return log.Errorf("parsePB() %s err %v", fullname, err)
}
if pb == nil {
log.Info("parsePB() == nil\n")
return log.Errorf("parsePB() == nil")
}
uuid := parts[1]
if argv.Clean != nil && argv.Clean.Match != "" {
if !strings.HasPrefix(uuid, argv.Clean.Match) {
return log.Errorf("uuid %s does not match %s", uuid, argv.Clean.Match)
}
}
if chat := me.chats.FindUuid(uuid); chat != nil {
log.Info("found uuid in chat", uuid, pb.Model, chat.Uuid)
statf, err := os.Stat(fullname)
if err == nil {
age := statf.ModTime()
if chat.AddGeminiRequest(fname, age, pb) {
me.chats.ConfigSave()
} else {
log.Info("file was perfect. os.Remove() here", fullname)
chat.PrintChatGeminiTable()
os.Remove(fullname)
}
}
return nil
}
id := parts[3]
if id == "1" {
log.Info("Insert new chat here", fullname, id)
statf, err := os.Stat(fullname)
if err == nil {
age := statf.ModTime()
c := new(chatpb.Chat)
c.Ctime = timestamppb.New(age)
c.Uuid = uuid
c.ChatName = "auto clean"
log.Info("new chat:", c.Uuid, c.Ctime)
me.chats.Append(c)
me.chats.ConfigSave()
okExit("")
}
}
log.Info("gemini JSON file uuid not found", fullname, id)
return log.Errorf("gemini JSON file uuid %s not found", uuid)
}

136
doConnect.go Normal file
View File

@ -0,0 +1,136 @@
package main
import (
"context"
"fmt"
"os"
"go.wit.com/lib/protobuf/chatpb"
"go.wit.com/log"
"google.golang.org/genai"
)
func initGeminiAPI() error {
if me.ctx != nil {
// already initialized
return nil
}
apiKey := os.Getenv("GEMINI_API_KEY")
if apiKey == "" {
return log.Errorf("GEMINI_API_KEY environment variable not set")
}
me.ctx = context.Background()
var err error
me.client, err = genai.NewClient(me.ctx, &genai.ClientConfig{APIKey: apiKey})
if err != nil {
return log.Errorf("failed to create new genai client: %w", err)
}
return nil
}
// doConnect initializes the Gemini client and handles the request flow.
func doConnect() error {
initGeminiAPI()
if me.lastChat == nil {
log.Info("WTF. lastChat is nil")
return nil
}
// if me.lastChat.Entries == nil {
// me.lastChat.Entries = new(chatpb.ChatEntry)
// }
// In a real application, you would get user input here.
// For now, we'll use a hardcoded prompt.
if len(me.lastChat.GetEntries()) == 0 {
me.lastChat.Entries = append(me.lastChat.Entries, &chatpb.ChatEntry{
Parts: []*chatpb.Part{
{PartType: &chatpb.Part_Text{Text: "hello, how are you"}},
},
})
}
lastEntry := me.lastChat.GetEntries()[len(me.lastChat.GetEntries())-1]
genaiContents, err := convertToGenai(lastEntry.GetGeminiRequest())
if err != nil {
return err
}
resp, err := me.client.Models.GenerateContent(me.ctx, "gemini-2.5-flash", genaiContents, nil)
if err != nil {
return log.Errorf("error sending message: %v", err)
}
if resp == nil || len(resp.Candidates) == 0 || resp.Candidates[0].Content == nil {
log.Info("Received an empty response from the API. Stopping.")
return nil
}
// Append the model's response to the history
me.lastChat.Entries = append(me.lastChat.Entries, convertToPB(resp))
// Check for a function call
hasFunctionCall := false
for _, part := range resp.Candidates[0].Content.Parts {
if fc := part.FunctionCall; fc != nil {
hasFunctionCall = true
functionResponse := handleFunctionCall(fc)
// Append the function response to the history for the next turn
me.lastChat.Entries = append(me.lastChat.Entries, &chatpb.ChatEntry{
Parts: []*chatpb.Part{
{PartType: &chatpb.Part_FunctionResponse{
FunctionResponse: &chatpb.FunctionResponse{
Name: functionResponse.Name,
// TODO: map response
},
}},
},
})
}
}
// If there was no function call, print the text and stop.
if !hasFunctionCall {
log.Info("Response from API:")
for _, cand := range resp.Candidates {
if cand.Content != nil {
for _, part := range cand.Content.Parts {
if part.Text != "" {
fmt.Println(part.Text)
}
}
}
}
}
return nil
}
// sampleHello sends a hardcoded prompt to the model and prints the response.
func simpleHello() error {
log.Info("Sending 'hello, how are you' to the Gemini API...")
// Create the parts slice
parts := []*genai.Part{
{Text: "What is my brothers name?"},
}
content := []*genai.Content{{Parts: parts}}
resp, err := me.client.Models.GenerateContent(me.ctx, "gemini-2.5-flash", content, nil)
if err != nil {
return log.Errorf("error sending message: %v", err)
}
log.Info("Response from API:")
for _, cand := range resp.Candidates {
if cand.Content != nil {
for _, part := range cand.Content.Parts {
fmt.Println(part)
}
}
}
return nil
}

104
doGui.go Normal file
View File

@ -0,0 +1,104 @@
// Copyright 2017-2025 WIT.COM Inc. All rights reserved.
// Use of this source code is governed by the GPL 3.0
package main
// An app to submit patches for the 30 GO GUI repos
import (
"fmt"
"os"
"time"
"go.wit.com/gui"
"go.wit.com/lib/debugger"
"go.wit.com/lib/gadgets"
"go.wit.com/lib/gui/logsettings"
"go.wit.com/lib/gui/shell"
"go.wit.com/log"
)
func debug() {
time.Sleep(2 * time.Second)
for {
log.Info("idle loop() todo: could check for things here")
time.Sleep(90 * time.Second)
}
}
func doGui() {
me.myGui = gui.New()
// me.myGui.SetAppDefaultPlugin(me.forge.Config.DefaultGui)
me.myGui.Default()
win := gadgets.NewGenericWindow("regex: a WIT Cloud private AI tool", "Current Conversations")
drawWindow(win)
win.Custom = func() {
log.Warn("MAIN WINDOW CLOSE")
me.myGui.StandardExit()
os.Exit(0)
}
me.mainWindow = win
// sits here forever
debug()
}
func drawWindow(win *gadgets.GenericWindow) {
grid := win.Group.RawGrid()
grid.NewLabel("label worked")
grid.NextRow()
var insertWin *gadgets.GenericWindow
s := fmt.Sprintf("Show Chat Entries (%d)", me.chats.Len())
grid.NewButton(s, func() {
// if the window exists, just toggle it open or closed
if insertWin != nil {
insertWin.Toggle()
return
}
insertWin = makeChatsWindow()
})
grid.NewButton("simple hello", func() {
err := simpleHello()
if err != nil {
badExit(err)
}
})
grid.NewButton("submit question", func() {
doEditorOnce()
})
grid.NewButton("print playback", func() {
shell.RunVerbose([]string{"regex", "playback"})
})
grid.NewButton("clean", func() {
doClean()
})
grid.NextRow()
grid.NewButton("debugger", func() {
debugger.DebugWindow()
})
grid.NewButton("logging", func() {
logsettings.LogWindow()
})
}
// old things before they are removed, deprecated, fixed, etc
func makeOldStuff() *gadgets.GenericWindow {
oldWin := gadgets.NewGenericWindow("old code", "old code on it's way out")
grid := oldWin.Group.RawGrid()
grid.NewButton("Release Window", func() {
log.Info("todo: move releaser here")
})
return oldWin
}

92
doInteract.go Normal file
View File

@ -0,0 +1,92 @@
package main
import (
"io/ioutil"
"os"
"os/exec"
"strings"
"time"
"go.wit.com/log"
)
func doInteract() error {
for {
filename, err := doEditorOnce()
if err != nil {
return err
}
log.Info("filename:", filename)
for {
_, err := os.Stat("/tmp/regex.ready")
if err == nil {
break
}
time.Sleep(100 * time.Millisecond)
}
// read in regex.ready exists (should be SessionID)
// Println session ID
content, err := ioutil.ReadFile("/tmp/regex.ready")
if err != nil {
log.Error(err)
}
os.Remove("/tmp/regex.ready")
log.Info("SessionID: %s", string(content))
logContent, err := ioutil.ReadFile("/tmp/regex.log")
if err != nil {
log.Errorf("could not read regex.log: %v", err)
} else {
log.Info("contents of /tmp/regex.log:")
os.Stdout.Write(logContent)
}
time.Sleep(5 * time.Second)
}
}
func doEditorOnce() (string, error) {
// Create a temporary file
tmpfile, err := ioutil.TempFile("", "regex-*.txt")
if err != nil {
return "", err
}
tmpPath := tmpfile.Name()
// Defer removal in case of error, but we might move it
defer os.Remove(tmpPath)
tmpfile.Close()
// Get the user's editor
editor := os.Getenv("EDITOR")
if editor == "" {
editor = "vim" // default to vim
}
// Run the editor
cmd := exec.Command(editor, tmpPath)
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
return "", err
}
// Read the file content
content, err := ioutil.ReadFile(tmpPath)
if err != nil {
return "", err
}
// Check if the file is not empty after trimming space
if strings.TrimSpace(string(content)) != "" {
// Move the file
if err := os.Rename(tmpPath, "/tmp/regex.txt"); err != nil {
return "", err
}
return "/tmp/regex.txt", nil
}
return "", nil
}

43
doJSON.go Normal file
View File

@ -0,0 +1,43 @@
// Copyright 2017-2025 WIT.COM Inc. All rights reserved.
// Use of this source code is governed by the GPL 3.0
package main
// An app to submit patches for the 30 GO GUI repos
import (
"path/filepath"
"strconv"
"strings"
"go.wit.com/lib/protobuf/chatpb"
"go.wit.com/log"
)
func doJSON() {
// now try to Marshal() into a protobuf
pb, err := parsePB(argv.JsonFile)
if err != nil {
badExit(err)
}
log.Info("GeminiContent pb.Marshal() worked pb.Contents len =", len(pb.Contents))
_, filename := filepath.Split(argv.JsonFile)
parts := strings.Split(filename, ".")
if len(parts) == 5 {
uuid := parts[1]
num, _ := strconv.Atoi(parts[3])
log.Info(uuid, parts)
if chat := me.chats.FindByUuid(uuid); chat != nil {
log.Info("FOUND CHAT", uuid, num)
newEntry := new(chatpb.ChatEntry)
newEntry.GeminiRequest = pb
newEntry.ContentFile = filename
newEntry.RequestCounter = int32(num)
chat.AppendEntry(newEntry)
me.chats.ConfigSave()
}
} else {
}
okExit("")
}

24
doNewChat.go Normal file
View File

@ -0,0 +1,24 @@
package main
import (
"go.wit.com/lib/protobuf/chatpb"
"go.wit.com/log"
"google.golang.org/protobuf/types/known/timestamppb"
)
func doNewChat() {
if found := me.chats.FindByUuid(argv.Uuid); found != nil {
found.ChatName = argv.Topic
me.chats.ConfigSave()
return
}
chat := &chatpb.Chat{
Uuid: argv.Uuid,
ChatName: argv.Topic,
Ctime: timestamppb.Now(),
}
me.chats.Chats = append(me.chats.Chats, chat)
me.chats.ConfigSave()
log.Info("created new chat for", argv.Uuid)
}

56
doOutput.go Normal file
View File

@ -0,0 +1,56 @@
package main
import (
"os"
"time"
"go.wit.com/lib/protobuf/chatpb"
"go.wit.com/log"
"google.golang.org/protobuf/types/known/timestamppb"
)
func doOutput(s string) {
filename := "/tmp/regex-output.log"
f, err := os.OpenFile(filename, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
log.Println(err)
return
}
defer f.Close()
if _, err := f.WriteString(s + "\n"); err != nil {
log.Println(err)
}
log.Info("OUTPUT LOGGED TO", filename)
// Load the existing chats.
all := chatpb.NewChats()
if err := all.ConfigLoad(); err != nil {
log.Warn("Error loading config, can't add to auto chat:", err)
return
}
// Find the "auto" chat.
var autoChat *chatpb.Chat
for _, chat := range all.GetChats() {
if chat.GetChatName() == "auto" {
autoChat = chat
break
}
}
// If the "auto" chat is found, add the new entry.
if autoChat != nil {
newEntry := &chatpb.ChatEntry{
From: chatpb.Who_REGEX,
Content: s,
Ctime: timestamppb.New(time.Now()),
}
autoChat.Entries = append(autoChat.Entries, newEntry)
if err := all.ConfigSave(); err != nil {
log.Warn("Error saving config after adding to auto chat:", err)
} else {
log.Info("Added new entry to 'auto' chat.")
}
}
}

151
doPlayback.go Normal file
View File

@ -0,0 +1,151 @@
package main
import (
"strings"
"go.wit.com/lib/protobuf/chatpb"
"go.wit.com/log"
)
func doPlayback() error {
if argv.Uuid != "" {
showChat(argv.Uuid)
return nil
}
if argv.Playback.Purge != nil {
doPurge()
return nil
}
listChats(me.chats)
return nil
}
func doPurge() {
changed := false
for _, chat := range me.chats.GetChats() {
if len(chat.GetEntries()) == 0 {
me.chats.Delete(chat)
changed = true
}
}
if changed {
me.chats.ConfigSave()
}
}
func showChat(uuid string) {
chat := me.chats.FindByUuid(uuid)
if chat == nil {
log.Info("unknown uuid", uuid)
return
}
prettyFormatChat(chat)
}
func listChats(chats *chatpb.Chats) {
if argv.Playback.Long != nil {
for _, chat := range chats.GetChats() {
listEntries(chat)
}
return
}
log.Info("Found %d chat topic(s) in the log.", len(chats.GetChats()))
log.Println("-------------------------------------------------")
for _, chat := range chats.GetChats() {
entryCount := len(chat.GetEntries())
var formattedTime string
if ctime := chat.GetCtime(); ctime != nil {
t := ctime.AsTime()
formattedTime = t.Format("2006-01-02 15:04:05")
} else {
formattedTime = "No Timestamp"
}
log.Printf("Entries: %-4d | Started: %-25s | UUID: %s | %-25s\n",
entryCount,
formattedTime,
chat.GetUuid(),
chat.GetChatName(),
)
}
log.Println("-------------------------------------------------")
// Get the last chat
numChats := len(chats.GetChats())
if numChats > 0 {
me.lastChat = chats.GetChats()[numChats-1]
log.Printf("The current Gemini API session is UUID: %s\n", me.lastChat.GetUuid())
dumpchat(me.lastChat)
}
}
// print out one line for each chat entry
func listEntries(chat *chatpb.Chat) {
log.Printf("--- Entries for Topic: %s ---\n", chat.GetChatName())
width := getTerminalWidth()
// Determine the maximum length of the author and time string
maxAuthorAndTimeLen := 0
for _, entry := range chat.GetEntries() {
author := entry.GetFrom().String()
var formattedTime string
if ctime := entry.GetCtime(); ctime != nil {
t := ctime.AsTime()
formattedTime = t.Format("2006-01-02 15:04:05")
} else {
formattedTime = "No Time"
}
authorAndTime := log.Sprintf("[%s] (%s)", author, formattedTime)
if len(authorAndTime) > maxAuthorAndTimeLen {
maxAuthorAndTimeLen = len(authorAndTime)
}
}
for _, entry := range chat.GetEntries() {
author := entry.GetFrom().String()
var formattedTime string
if ctime := entry.GetCtime(); ctime != nil {
t := ctime.AsTime()
formattedTime = t.Format("2006-01-02 15:04:05")
} else {
formattedTime = "No Time"
}
// Create a short preview of the content
contentPreview := strings.TrimSpace(entry.GetContent())
// Replace newlines with spaces for a clean one-line view
contentPreview = strings.ReplaceAll(contentPreview, "\n", " ")
authorAndTime := log.Sprintf("[%s] (%s)", author, formattedTime)
availableWidth := width - maxAuthorAndTimeLen - 1 // -1 for a space
if len(contentPreview) > availableWidth {
contentPreview = contentPreview[:availableWidth-3] + "..."
}
if author == "USER" {
// Calculate padding to fill the space between content and the right-aligned author/time
padding := width - len(contentPreview) - maxAuthorAndTimeLen
if padding < 0 {
padding = 0
}
// Calculate padding to align the author/time string itself
authorAndTimePadding := maxAuthorAndTimeLen - len(authorAndTime)
if authorAndTimePadding < 0 {
authorAndTimePadding = 0
}
log.Printf("%s%s%s%s\n", contentPreview, strings.Repeat(" ", padding), strings.Repeat(" ", authorAndTimePadding), authorAndTime)
} else {
padding := maxAuthorAndTimeLen - len(authorAndTime)
if padding < 0 {
padding = 0
}
log.Printf("%s%s %s\n", authorAndTime, strings.Repeat(" ", padding), contentPreview)
}
}
log.Println("-------------------------------------------------")
}

44
doStats.go Normal file
View File

@ -0,0 +1,44 @@
package main
import (
"encoding/json"
"go.wit.com/lib/protobuf/chatpb"
"go.wit.com/log"
"google.golang.org/protobuf/types/known/timestamppb"
)
func doStats() {
sessionUuid := argv.Uuid
statsString := "todo: set this somehow"
// Find the "auto" chat, or create it if it doesn't exist.
var autoChat *chatpb.Chat
for _, chat := range me.chats.GetChats() {
if chat.GetChatName() == "auto" {
autoChat = chat
break
}
}
if autoChat == nil {
autoChat = &chatpb.Chat{
ChatName: "auto",
Ctime: timestamppb.Now(),
}
me.chats.Chats = append(me.chats.Chats, autoChat)
}
var stats chatpb.SessionStats
err := json.Unmarshal([]byte(statsString), &stats)
if err != nil {
log.Printf("error unmarshalling stats: %w", err)
return
}
// The session UUID from the command line is the UUID of the session.
stats.Uuid = sessionUuid
autoChat.Session = append(autoChat.Session, &stats)
me.chats.ConfigSave()
log.Info("stats saved for session", sessionUuid, "in chat", autoChat.GetChatName())
}

39
dumpchat.go Normal file
View File

@ -0,0 +1,39 @@
package main
import (
"go.wit.com/lib/protobuf/chatpb"
"go.wit.com/log"
)
func dumpEntry(entry *chatpb.ChatEntry) {
log.Printf(entry.FormatTEXT())
}
func dumpchat(chat *chatpb.Chat) error {
entries := chat.GetEntries()
var lastEntry *chatpb.ChatEntry
if len(entries) > 0 {
lastEntry = entries[len(entries)-1]
} else {
return log.Errorf("no entries")
}
if argv.Playback.Last != nil {
dumpEntry(lastEntry)
}
if argv.Playback.Submit != nil {
if lastEntry.GeminiRequest == nil {
return log.Errorf("lastEntry.GeminiRequest == nil")
}
aichat, err := convertToGenai(lastEntry.GetGeminiRequest())
if err != nil {
log.Info("convertToGenai() returned with error", err)
return err
}
err = submitChat(aichat)
if err != nil {
log.Info("submitChat() returned with error", err)
return err
}
}
return nil
}

View File

@ -11,12 +11,12 @@ import (
func okExit(thing string) {
if thing != "" {
log.Info("gemini exit:", thing, "ok")
log.Info("regex exit:", thing, "ok")
}
os.Exit(0)
}
func badExit(err error) {
log.Info("gemini failed: ", err)
log.Info("regex failed: ", err)
os.Exit(-1)
}

22
getNextAutoTopic.go Normal file
View File

@ -0,0 +1,22 @@
package main
import (
"strconv"
"strings"
"go.wit.com/log"
)
func getNextAutoTopic() {
max := 0
for _, chat := range me.chats.GetChats() {
if strings.HasPrefix(chat.GetChatName(), "Auto ") {
numStr := strings.TrimPrefix(chat.GetChatName(), "Auto ")
num, err := strconv.Atoi(numStr)
if err == nil && num > max {
max = num
}
}
}
log.Printf("Auto %d", max+1)
}

51
handleFunctionCall.go Normal file
View File

@ -0,0 +1,51 @@
package main
import (
"fmt"
"go.wit.com/log"
"google.golang.org/genai"
)
// handleFunctionCall executes a command requested by the Gemini API and returns the result.
func handleFunctionCall(fc *genai.FunctionCall) *genai.FunctionResponse {
if fc == nil {
return nil
}
if fc.Name != "run_shell_command" {
log.Infof("Unsupported function call: %s", fc.Name)
return &genai.FunctionResponse{
Name: fc.Name,
Response: map[string]any{
"error": fmt.Sprintf("Unsupported function call: %s", fc.Name),
},
}
}
// Extract arguments
cmd, _ := fc.Args["command"].(string)
dir, _ := fc.Args["directory"].(string)
if cmd == "" {
return &genai.FunctionResponse{
Name: fc.Name,
Response: map[string]any{
"error": "missing command argument",
},
}
}
// Execute the command (this is a placeholder for the actual execution)
// In a real implementation, you would use the run_shell_command tool here.
log.Infof("Executing command: '%s' in directory: '%s'", cmd, dir)
// For now, we'll return a dummy response.
// TODO: Replace this with actual command execution.
return &genai.FunctionResponse{
Name: fc.Name,
Response: map[string]any{
"output": "command executed successfully (dummy response)",
},
}
}

125
json.go Normal file
View File

@ -0,0 +1,125 @@
package main
import (
"encoding/json"
"os"
"go.wit.com/lib/protobuf/chatpb"
"go.wit.com/log"
)
// GeminiRequest matches the overall structure of the gemini-cli JSON output.
type GeminiRequest struct {
Model string `json:"model"`
Contents []Content `json:"contents"`
// Config is left as a raw message because its structure is complex and not needed for now.
Config json.RawMessage `json:"config"`
}
// Content matches the 'contents' array elements.
type Content struct {
Role string `json:"role"`
Parts []Part `json:"parts"`
}
// Part matches the 'parts' array elements.
// It can contain one of several types of data.
type Part struct {
Text string `json:"text,omitempty"`
ThoughtSignature string `json:"thoughtSignature,omitempty"`
FunctionCall *FunctionCall `json:"functionCall,omitempty"`
FunctionResponse *FunctionResponse `json:"functionResponse,omitempty"`
}
// FunctionCall matches the 'functionCall' object.
type FunctionCall struct {
Name string `json:"name"`
Args map[string]string `json:"args"`
}
// FunctionResponse matches the 'functionResponse' object.
type FunctionResponse struct {
ID string `json:"id"`
Name string `json:"name"`
Response map[string]interface{} `json:"response"`
}
func parsePB(filename string) (*chatpb.GeminiRequest, error) {
// Read the entire file
data, err := os.ReadFile(filename)
if err != nil {
return nil, log.Errorf("failed to read file %s: %w", filename, err)
}
pb := new(chatpb.GeminiRequest)
if err := pb.UnmarshalJSON(data); err != nil {
return nil, err
}
return pb, nil
}
// parseJSON opens the given file, reads it, and unmarshals it into our structs.
func parseJSON(filename string) (*GeminiRequest, error) {
log.Infof("Attempting to parse file: %s\n", filename)
// Read the entire file
data, err := os.ReadFile(filename)
if err != nil {
return nil, log.Errorf("failed to read file %s: %w", filename, err)
}
// Unmarshal the JSON data
var req *GeminiRequest
req = new(GeminiRequest)
if err := json.Unmarshal(data, &req); err != nil {
return nil, log.Errorf("failed to unmarshal JSON from %s: %w", filename, err)
}
dumpSummaryJSON(req)
return req, nil
}
func dumpSummaryJSON(req *GeminiRequest) {
var totalFC, totalTexts, totalFR int
// Log the parsed data to confirm it worked
// Example of accessing deeper data
for _, content := range req.Contents {
// log.Infof("Content[%d] Role: %s", i, content.Role)
for _, part := range content.Parts {
if part.Text != "" {
// log.Infof(" Part[%d] Text: %.60s...", j, part.Text) // Print snippet
totalTexts += 1
}
if part.FunctionCall != nil {
// log.Infof(" Part[%d] FunctionCall: %s", j, part.FunctionCall.Name)
totalFC += 1
}
if part.FunctionResponse != nil {
// log.Infof(" Part[%d] FunctionCall: %s", j, part.FunctionCall.Name)
totalFR += 1
}
}
}
log.Printf("Parsed JSON (Model: %s) (# of content blocks %d) (Text #=%d) (FC=%d) (FR=%d)\n", req.Model, len(req.Contents), totalTexts, totalFC, totalFR)
}
func dumpFullJSON(req *GeminiRequest) {
// Log the parsed data to confirm it worked
log.Info("Successfully parsed JSON file.")
log.Infof("Model: %s", req.Model)
log.Infof("Number of content blocks: %d", len(req.Contents))
// Example of accessing deeper data
for i, content := range req.Contents {
log.Infof("Content[%d] Role: %s", i, content.Role)
for j, part := range content.Parts {
if part.Text != "" {
log.Infof(" Part[%d] Text: %.60s...", j, part.Text) // Print snippet
}
if part.FunctionCall != nil {
log.Infof(" Part[%d] FunctionCall: %s", j, part.FunctionCall.Name)
}
}
}
}

99
main.go
View File

@ -8,11 +8,11 @@ package main
import (
"embed"
"os"
"strings"
"github.com/google/uuid"
"go.wit.com/dev/alexflint/arg"
"go.wit.com/gui"
"go.wit.com/lib/protobuf/gitpb"
"go.wit.com/lib/protobuf/chatpb"
"go.wit.com/log"
)
@ -26,21 +26,13 @@ var BUILDTIME string
var resources embed.FS
// used for shell auto completion
var ARGNAME string = "gemini"
var ARGNAME string = "regex"
// using this for now. triggers config save
var configSave bool
func getVersion(repo *gitpb.Repo, name string) string {
cmd := []string{"git", "describe", "--tags", "--always", name}
result, _ := repo.RunQuiet(cmd)
output := strings.Join(result.Stdout, "\n")
log.Info("cmd =", cmd, output)
return strings.TrimSpace(output)
}
func main() {
var err error
me = new(mainType)
gui.InitArg()
me.pp = arg.MustParse(&argv)
@ -54,18 +46,89 @@ func main() {
os.Exit(0)
}
// load the default chat protobuf
me.chats = chatpb.NewChats()
if err := me.chats.ConfigLoad(); err != nil {
badExit(err)
}
// verify all the chats have Uuid's
if verifyUuids(me.chats) {
me.chats.ConfigSave()
}
// Get the last chat
numChats := len(me.chats.GetChats())
if numChats > 0 {
me.lastChat = me.chats.GetChats()[numChats-1]
log.Printf("The current Gemini API session is UUID: %s\n", me.lastChat.GetUuid())
}
err = initGeminiAPI()
if err != nil {
badExit(err)
}
if argv.JsonFile != "" {
doJSON()
okExit("")
}
if argv.Interact != nil {
log.Info("testing AI client with simpleHello()")
err = simpleHello()
if err != nil {
badExit(err)
}
doInteract()
okExit("")
}
if argv.Stats != "" {
doStats()
okExit("")
}
if argv.NewChat != nil {
doNewChat()
okExit("")
}
if argv.Playback != nil {
log.Info("do playback here")
if argv.Uuid != "" {
showChat(argv.Uuid)
} else {
doPlayback()
}
okExit("")
}
if argv.Add != nil {
log.Info("add new conversation to protobuf")
if argv.Clean != nil {
doClean()
okExit("")
}
// if opening the GUI, always check git for dirty repos
log.Info("open the gui here")
// doGui()
doGui()
// by default, start interacting with gemini-cli
// me.pp.WriteHelp(os.Stdout)
okExit("")
}
func verifyUuids(chats *chatpb.Chats) bool {
var changed bool
for _, chat := range chats.GetChats() {
if chat.GetUuid() == "" {
chat.Uuid = uuid.New().String()
changed = true
}
for _, entry := range chat.GetEntries() {
if entry.GetUuid() == "" {
entry.Uuid = uuid.New().String()
changed = true
}
}
}
return changed
}

199
prettyFormat.go Normal file
View File

@ -0,0 +1,199 @@
// This file contains functions for formatting and printing chat logs to the terminal.
// These functions operate exclusively on the in-memory protobuf data structures.
// They do NOT access the filesystem; all content (from content files, snippets, etc.)
// is expected to have been loaded into the 'Content' fields of the protobuf messages
// before these functions are called.
package main
import (
"path/filepath"
"strings"
"go.wit.com/lib/protobuf/chatpb"
"go.wit.com/log"
)
const termWidth = 100 // The target width for the formatted output boxes.
// prettyFormatChat is the main entry point to print a detailed view of a Chat topic.
func prettyFormatChat(chat *chatpb.Chat) {
log.Printf("\n========================================================\n")
log.Printf("== Chat Topic: %s (UUID: %s)\n", chat.GetChatName(), chat.GetUuid())
log.Printf("========================================================\n\n")
for _, entry := range chat.GetEntries() {
author := entry.GetFrom().String()
var formattedTime string
if ctime := entry.GetCtime(); ctime != nil {
t := ctime.AsTime()
formattedTime = t.Format("2006-01-02 15:04:05")
} else {
formattedTime = "No Timestamp"
}
// Use the in-memory Content field directly.
content := entry.GetContent()
if content != "" {
printContent(author, formattedTime, content)
}
if table := entry.GetTable(); table != nil {
printTable(table)
}
for _, toolCall := range entry.GetToolCalls() {
printToolCallBox(toolCall)
}
if snippets := entry.GetSnippets(); snippets != nil {
for _, snippet := range snippets {
printCodeSnippet(snippet)
}
}
log.Println()
}
}
// printContent handles the wrapping for the main conversational text.
func printContent(author, timestamp, content string) {
// Right-align USER messages, left-align REGEX messages.
if author == "USER" {
printRightAligned(author, timestamp, content)
} else {
printLeftAligned(author, timestamp, content)
}
}
func printLeftAligned(author, timestamp, content string) {
prefix := log.Sprintf("✦ %s (%s):", author, timestamp)
log.Println(prefix)
indent := "\t"
contentWidth := termWidth - 8 // 8 spaces for a standard tab
paragraphs := strings.Split(content, "\n")
for _, paragraph := range paragraphs {
words := strings.Fields(paragraph)
if len(words) == 0 {
log.Println() // Preserve paragraph breaks
continue
}
currentLine := indent + words[0]
for _, word := range words[1:] {
if len(currentLine)+1+len(word) <= contentWidth {
currentLine += " " + word
} else {
log.Println(currentLine)
currentLine = indent + word
}
}
log.Println(currentLine)
}
}
func printRightAligned(author, timestamp, content string) {
prefix := log.Sprintf("(%s) %s ✦", timestamp, author)
// Print the prefix first, right-aligned.
log.Printf("%*s\n", termWidth, prefix)
// The available width for the text.
contentWidth := termWidth - 8 // Leave a tab's worth of margin on the left
paragraphs := strings.Split(content, "\n")
for _, paragraph := range paragraphs {
words := strings.Fields(paragraph)
if len(words) == 0 {
log.Println() // Preserve paragraph breaks
continue
}
currentLine := words[0]
for _, word := range words[1:] {
if len(currentLine)+1+len(word) <= contentWidth {
currentLine += " " + word
} else {
// Print the completed line, right-aligned.
log.Printf("%*s\n", termWidth, currentLine)
currentLine = word
}
}
// Print the last remaining line of the paragraph, right-aligned.
log.Printf("%*s\n", termWidth, currentLine)
}
}
func printTable(table *chatpb.Table) {
if table == nil || len(table.GetRows()) == 0 {
return
}
log.Println("┌─[ Table Data ]──────────────────────────────────────────")
for _, row := range table.GetRows() {
log.Printf("│ %s\n", strings.Join(row.GetFields(), " │ "))
}
log.Printf("└─────────────────────────────────────────────────────────\n\n")
}
func printCodeSnippet(snippet *chatpb.CodeSnippet) {
// Use the in-memory Content field directly.
code := snippet.GetContent()
language := filepath.Base(snippet.GetFilename()) // Still useful for display
log.Println() // Add extra line feed for spacing
// --- Top Border ---
topBorder := log.Sprintf("┌─[ Code Snippet: %s ]", language)
log.Printf("%s%s┐\n", topBorder, strings.Repeat("─", termWidth-len(topBorder)-1))
// --- Content Lines ---
for _, line := range strings.Split(strings.TrimSpace(code), "\n") {
// Calculate padding: total width - borders/padding - text length
padding := termWidth - 4 - len(line)
if padding < 0 {
padding = 0 // Should not happen with wrapping, but as a safeguard
}
log.Printf("│ %s%s │\n", line, strings.Repeat(" ", padding))
}
// --- Bottom Border ---
log.Printf("└%s┘\n\n", strings.Repeat("─", termWidth-2))
}
func printToolCallBox(tc *chatpb.ToolCall) {
boxWidth := termWidth - 2
log.Printf(" ╭%s╮\n", strings.Repeat("─", boxWidth))
header := log.Sprintf(" ✔ %s %s (%s)", tc.GetName(), tc.GetInput(), tc.GetDescription())
printWrappedLine(header, boxWidth)
printEmptyLine(boxWidth)
if stdout := tc.GetOutputStdout(); stdout != "" {
for _, line := range strings.Split(stdout, "\n") {
printWrappedLine(" "+line, boxWidth)
}
}
if stderr := tc.GetOutputStderr(); stderr != "" {
for _, line := range strings.Split(stderr, "\n") {
printWrappedLine(" "+line, boxWidth)
}
}
printEmptyLine(boxWidth)
log.Printf(" ╰%s╯\n", strings.Repeat("─", boxWidth))
}
func printWrappedLine(text string, width int) {
if len(text) == 0 {
printEmptyLine(width)
return
}
for len(text) > width {
log.Printf(" │ %-*s │\n", width, text[:width])
text = text[width:]
}
log.Printf(" │ %-*s │\n", width, text)
}
func printEmptyLine(width int) {
log.Printf(" │ %*s │\n", width, "")
}

69
stats.go Normal file
View File

@ -0,0 +1,69 @@
package main
/*
// The following are the Go equivalents of the gemini-cli's TypeScript
// interfaces for session statistics. You can use these to collect and
// store metrics in your application.
// ToolCallDecision represents the user's decision on a tool call.
type ToolCallDecision string
const (
Accept ToolCallDecision = "accept"
Reject ToolCallDecision = "reject"
Modify ToolCallDecision = "modify"
AutoAccept ToolCallDecision = "auto_accept"
)
// ToolCallStats holds the statistics for a single tool.
type ToolCallStats struct {
Count int
Success int
Fail int
DurationMs int
Decisions map[ToolCallDecision]int
}
// ModelMetrics holds the statistics for a single model.
type ModelMetrics struct {
API struct {
TotalRequests int
TotalErrors int
TotalLatencyMs int
}
Tokens struct {
Prompt int
Candidates int
Total int
Cached int
Thoughts int
Tool int
}
}
// SessionMetrics holds all the statistics for a session.
type SessionMetrics struct {
Models map[string]ModelMetrics
Tools struct {
TotalCalls int
TotalSuccess int
TotalFail int
TotalDurationMs int
TotalDecisions map[ToolCallDecision]int
ByName map[string]ToolCallStats
}
Files struct {
TotalLinesAdded int
TotalLinesRemoved int
}
}
// You will need to initialize and update this struct as your application
// makes API calls and runs tools.
var sessionMetrics SessionMetrics
// Example of how you might update the metrics after an API call:
// modelMetrics := sessionMetrics.Models["gemini-pro"]
// modelMetrics.API.TotalRequests++
// ... and so on.
*/

View File

@ -4,13 +4,24 @@
package main
import (
"context"
"go.wit.com/dev/alexflint/arg"
"go.wit.com/gui"
"go.wit.com/lib/gadgets"
"go.wit.com/lib/protobuf/chatpb"
"google.golang.org/genai"
)
var me *mainType
// this app's variables
type mainType struct {
pp *arg.Parser // for parsing the command line args. Yay to alexf lint!
// myGui *gui.Node // the gui toolkit handle
pp *arg.Parser // for parsing the command line args. Yay to alexf lint!
chats *chatpb.Chats // all our prior conversations with regex
client *genai.Client // the Google Gemini AI client variable
ctx context.Context // global context. what does this acutally mean?
lastChat *chatpb.Chat // the last chat. append to here
myGui *gui.Node // the gui toolkit handle
mainWindow *gadgets.GenericWindow // the main GUI window
}

27
submitChat.go Normal file
View File

@ -0,0 +1,27 @@
package main
import (
"fmt"
"go.wit.com/log"
"google.golang.org/genai"
)
func submitChat(content []*genai.Content) error {
resp, err := me.client.Models.GenerateContent(me.ctx, "gemini-2.5-flash", content, nil)
if err != nil {
return log.Errorf("error sending message: %v", err)
}
log.Info("Response from API:")
for _, cand := range resp.Candidates {
if cand.Content != nil {
for _, part := range cand.Content.Parts {
fmt.Println(part)
}
}
}
// TODO: add the response to the protobuf
addResponse(resp)
return nil
}

16
terminal_width.go Normal file
View File

@ -0,0 +1,16 @@
package main
import (
"os"
"golang.org/x/term"
)
func getTerminalWidth() int {
width, _, err := term.GetSize(int(os.Stdout.Fd()))
if err != nil {
// Return a default width if there's an error
return 80
}
return width
}

111
windowBook.go Normal file
View File

@ -0,0 +1,111 @@
// Copyright 2017-2025 WIT.COM Inc. All rights reserved.
// Use of this source code is governed by the GPL 3.0
package main
import (
"fmt"
"time"
"go.wit.com/lib/gadgets"
"go.wit.com/lib/protobuf/chatpb"
"go.wit.com/log"
)
func makeBookWindow(all *chatpb.Books) *gadgets.GenericWindow {
bookWin := gadgets.NewGenericWindow("regex Books", "Display Books")
bookWin.Win.Custom = func() {
log.Info("test delete window here")
}
grid := bookWin.Group.RawGrid()
var t *chatpb.BooksTable
grid.NewButton("show", func() {
if t != nil {
log.Info("Delete the table first")
return
}
// display the protobuf
t = addBooksPB(bookWin, all)
f := func(chat *chatpb.Book) {
log.Info("got to BookTable.Custom() id =", chat.GetUuid(), chat.GetTitle())
}
t.Custom(f)
log.Info("table has uuid", t.GetUuid())
})
grid.NewButton("delete PB table", func() {
if t != nil {
t.Delete()
t = nil
log.Info("Table should have been deleted")
}
})
// display the protobuf
t = addBooksPB(bookWin, all)
f := func(chat *chatpb.Book) {
log.Info("got to BookTable.Custom() id =", chat.GetUuid(), chat.GetTitle())
}
t.Custom(f)
log.Info("table has uuid", t.GetUuid())
return bookWin
}
func addBooksPB(win *gadgets.GenericWindow, pb *chatpb.Books) *chatpb.BooksTable {
t := pb.NewTable("testForgeRepos")
t.NewUuid()
tbox := win.Bottom.Box().SetProgName("TBOX")
t.SetParent(tbox)
sf := t.AddStringFunc("uuid", func(r *chatpb.Book) string {
return r.GetUuid()
})
sf.Custom = func(r *chatpb.Book) {
log.Info("todo: fix mouseClick() on stringFunc in GUI table", r.GetUuid())
}
// add a general show button
bf := t.AddButtonFunc("cur version", func(chat *chatpb.Book) string { return "submit" })
bf.Custom = func(book *chatpb.Book) {
log.Info("convert pb to genai GO API HERE", book.GetUuid())
if book.GetGeminiRequest() == nil {
return
}
aichat, err := convertToGenai(book.GetGeminiRequest())
if err != nil {
log.Info("convertToGenai() returned with error", err)
return
}
err = submitChat(aichat)
if err != nil {
log.Info("submitChat() returned with error", err)
return
}
log.Info("submitChat() appears to have worked?")
}
// show the age of the chat
t.AddTimeFunc("age", func(book *chatpb.Book) time.Time {
return book.GetCtime().AsTime()
})
t.AddTitle()
// t.AddVersion()
// make a button to show content in the *genai.GeminiRequest structures
genaiButton := t.AddButtonFunc("# of parts", func(book *chatpb.Book) string {
if book.GeminiRequest == nil {
return "nil"
}
var req = book.GeminiRequest
return fmt.Sprintf("%d", len(req.Contents))
})
genaiButton.Custom = func(book *chatpb.Book) {
log.Info("show *genai.GeminiRequsts for", book.GetUuid())
book.GeminiRequest.PrintGeminiTable()
}
// draw the tabel (send the gui protobuf to the GO plugin)
t.ShowTable()
return t
}

162
windowChats.go Normal file
View File

@ -0,0 +1,162 @@
// Copyright 2017-2025 WIT.COM Inc. All rights reserved.
// Use of this source code is governed by the GPL 3.0
package main
import (
"fmt"
"time"
"go.wit.com/lib/gadgets"
"go.wit.com/lib/protobuf/chatpb"
"go.wit.com/log"
)
/*
type stdReposTableWin struct {
sync.Mutex
win *gadgets.GenericWindow // the machines gui window
boxTB *gui.Node // the machines gui parent box widget
TB *gitpb.ReposTable // the gui table buffer
pb *gitpb.Repos // the current repos protobuf
update bool // if the window should be updated
}
func (w *stdReposTableWin) Toggle() {
if w == nil {
return
}
if w.win == nil {
return
}
w.win.Toggle()
}
*/
func makeChatsWindow() *gadgets.GenericWindow {
insertWin := gadgets.NewGenericWindow("regex Chats", "Display Chats")
insertWin.Win.Custom = func() {
log.Info("test delete window here")
insertWin.Hide()
}
grid := insertWin.Group.RawGrid()
var t *chatpb.ChatsTable
grid.NewButton("show", func() {
if t != nil {
log.Info("Delete the table first")
return
}
// display the protobuf
t = addChatsPB(insertWin, me.chats)
f := func(chat *chatpb.Chat) {
log.Info("got to ChatTable.Custom() id =", chat.GetUuid(), chat.GetChatName())
}
t.Custom(f)
log.Info("table has uuid", t.GetUuid())
})
grid.NewButton("delete PB table", func() {
if t != nil {
t.Delete()
t = nil
log.Info("Table should have been deleted")
}
})
// display the protobuf
t = addChatsPB(insertWin, me.chats)
f := func(chat *chatpb.Chat) {
log.Info("got to ChatTable.Custom() id =", chat.GetUuid(), chat.GetChatName())
}
t.Custom(f)
log.Info("table has uuid", t.GetUuid())
return insertWin
}
func addChatsPB(win *gadgets.GenericWindow, pb *chatpb.Chats) *chatpb.ChatsTable {
t := pb.NewTable("testForgeRepos")
t.NewUuid()
tbox := win.Bottom.Box().SetProgName("TBOX")
t.SetParent(tbox)
sf := t.AddStringFunc("uuid", func(r *chatpb.Chat) string {
return r.GetUuid()
})
sf.Custom = func(r *chatpb.Chat) {
log.Info("todo: fix mouseClick() on stringFunc in GUI table", r.GetUuid())
}
// add a general show button
bf := t.AddButtonFunc("cur version", func(chat *chatpb.Chat) string { return "show" })
bf.Custom = func(r *chatpb.Chat) {
log.Info("todo: show a chat window here", r.GetUuid())
}
// show the age of the chat
t.AddTimeFunc("age", func(chat *chatpb.Chat) time.Time {
return chat.GetCtime().AsTime()
})
t.AddChatName()
// make a button to show the ChatEntries
entryButton := t.AddButtonFunc("Entries", func(chat *chatpb.Chat) string {
return fmt.Sprintf("%d", len(chat.GetEntries()))
})
entryButton.Custom = func(chat *chatpb.Chat) {
log.Info("show entries for", chat.GetUuid())
chat.PrintChatEntriesTable()
}
// make a button to show the Stats (old stuff from gemini-cli)
statsButton := t.AddButtonFunc("Stats", func(chat *chatpb.Chat) string {
return fmt.Sprintf("%d", len(chat.GetSession()))
})
statsButton.Custom = func(chat *chatpb.Chat) {
log.Info("show gemini-cli /stats for", chat.GetUuid())
chat.PrintChatStatsTable()
}
// make a button to show content in the *genai.GeminiRequest structures
genaiButton := t.AddButtonFunc("# of genai.Req's", func(chat *chatpb.Chat) string {
var counter int
for _, entry := range chat.GetEntries() {
if entry.GeminiRequest != nil {
counter += 1
}
}
return fmt.Sprintf("%d", counter)
})
genaiButton.Custom = func(chat *chatpb.Chat) {
log.Info("show *genai.GeminiRequsts for", chat.GetUuid())
chat.PrintChatGeminiTable()
pb := makeBooksTable(chat)
makeBookWindow(pb)
}
// draw the tabel (send the gui protobuf to the GO plugin)
t.ShowTable()
return t
}
func makeBooksTable(chat *chatpb.Chat) *chatpb.Books {
var pb *chatpb.Books
pb = chatpb.NewBooks()
pb.TitleUuid = chat.Uuid
for _, entry := range chat.GetEntries() {
if entry.GeminiRequest == nil {
continue
}
newb := new(chatpb.Book)
newb.Ctime = entry.Ctime
newb.Uuid = entry.Uuid
newb.From = entry.From
newb.Title = entry.ContentFile
newb.GeminiRequest = entry.GeminiRequest
pb.Append(newb)
}
pb.ConfigSave()
return pb
}